package com.ceba.test.modules.filemanage.dao;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.ceba.base.constants.FileClassConstants;
import com.ceba.base.constants.FileFlagConstants;
import com.ceba.base.enums.GFileContentTypeEnum;
import com.ceba.base.helper.DBJSONHelper;
import com.ceba.base.helper.LoggerHelper;
import com.ceba.base.utils.PDFUtils;
import com.ceba.cebautils.DateUtil;
import com.ceba.cebautils.StringUtil;
import com.ceba.test.base.configs.CebaPathUtil;
import com.ceba.test.base.language.ResourceUtils;
import com.ceba.test.base.utils.CebaFileManageUtil;
import org.apache.commons.lang.StringUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ceba.test.base.configs.CebaConfig;
import com.ceba.test.base.constants.TextConstants;
import com.ceba.test.modules.filemanage.dto.VFileObject;
import com.ceba.test.modules.filemanage.entity.GFile;
import com.ceba.test.modules.filemanage.entity.GFileRelaction;
import com.ceba.test.modules.filemanage.entity.GFolder;

import abc.ID;
import abc.Result;
import abc.data.Commands;
import abc.data.DBAction;
import abc.data.DataRow;
import abc.data.DataTable;
import abc.data.Parameters;
import abc.data.Sql;
import abc.data.SqlSessionManager;
import abc.data.dataSource.SqlDataSource;
import abc.data.sql.DataTableSqlBuilder;
import abc.data.store.IStore;
import abc.data.store.StoreManager;
import abc.object.IObject;
import abc.object.XObject;
import abc.util.FileHelper;
import abc.util.Zip;

public class FileManagerDao extends GFileDao{
	
	static Logger logger = LoggerFactory.getLogger(FileManagerDao.class);
	
	/**
	 * 搜索文件夹中的目录和文件内容，全文检索
	 * 
	 * @param key 关键字
	 * @param path 目录路径，可以说空，空则默认全局
	 * @param otherLimit 其他限制条件，是一个sql查询条件语句
	 * @return
	 * @throws Exception
	 */
	public DataTable searchFolder(String key,String path,String otherLimit) {
		try{
			String folderTj1="";
			if(path==null || path.equals("")){
				folderTj1="(1=1) ";
			}
			else {
				folderTj1="(g_folder.NAME LIKE '" + path + "%' AND g_folder.NAME != '" + path + "')";
			}
			
			if(otherLimit==null){
				otherLimit="";
			}
			
			String folderTj2="";
			String fileTj1 = "";
			String[] arr = key.split(" ");
			for (String s : arr) {
				if (!s.equals("")) {
					folderTj2="AND (g_folder.FOLDER_NAME LIKE '%" + s + "%')";
					fileTj1 += " AND (IFNULL(g_file_relaction.FILE_NAME,g_file.FILE_NAME) LIKE '%" + s
							+ "%' OR g_file.TEXT_CONTENT LIKE '%" + s + "%')";
				}
			}
			
		  Sql sql=new Sql("SELECT g_folder.ID, FOLDER_NAME AS NAME,'' AS SIZE,g_folder.CREATE_TIME,g_folder.NAME AS PATH,CLASS,"
		  		    + "u_user.NAME AS USER_NAME,u_user.ID AS USER_ID,'0' AS FILE_TYPE,IMG "
					+ " from g_folder " 
					+ " LEFT OUTER JOIN u_user ON g_folder.CREATE_USER=u_user.ID" 
					+ " WHERE  " + folderTj1 + folderTj2 + otherLimit
					+ " UNION"
					+ " SELECT g_file_relaction.ID,IFNULL(g_file_relaction.FILE_NAME,g_file.FILE_NAME),SIZE,g_file_relaction.CREATE_TIME,"
					+ " CONCAT(g_folder.NAME,IFNULL(g_file_relaction.FILE_NAME,g_file.FILE_NAME)) AS PATH,g_file.CLASS,'' AS IMG,"
					+ " u_user.NAME AS USER_NAME,u_user.ID AS USER_ID,'1' AS FILE_TYPE"
					+ " FROM g_file_relaction"
					+ " LEFT OUTER JOIN g_folder ON g_file_relaction.FOLDER_ID=g_folder.ID"
					+ " LEFT OUTER JOIN g_file ON g_file_relaction.FILE_ID=g_file.ID"
					+ " LEFT OUTER JOIN u_user ON g_file_relaction.USER_ID=u_user.ID" 
					+ " WHERE  " + folderTj1 + fileTj1 + otherLimit);


	  		return SqlSessionManager.getDataTable(sql);
		}catch(Exception e){
			LoggerHelper.error(logger, e, "");
			return null;
		}
	}
	
	/**
	 * 获取目录的子文件与子目录（当前目录的）
	 * 
	 * @param pathOrId 目录的路径或目录ID
	 * 
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public List<VFileObject> getFolder(String pathOrId) {
		List<VFileObject> vfList= new ArrayList();
		try{
			if(pathOrId==null || pathOrId.equals("")){
				return null;
			}
			String id="";
			String name="";
			Sql sql=new Sql("SELECT ID,NAME FROM g_folder WHERE ID='"+pathOrId+"' OR NAME='"+pathOrId+"'");
			
			DataTable dtFolder=SqlSessionManager.getDataTable(sql);
			if(dtFolder!=null && dtFolder.getRowCount()>0){
				id=dtFolder.getRow(0).getString("ID");
				name=dtFolder.getRow(0).getString("NAME");
			}
			
			sql=new Sql("SELECT * FROM (SELECT g_folder.ID, FOLDER_NAME AS NAME,'' AS SIZE,"
					+ " g_folder.CREATE_TIME,g_folder.NAME AS PATH,"
					+ " CLASS,'' AS EXT_NAME,u_user.NAME AS USER_NAME,u_user.ID AS USER_ID,'0' AS FILE_TYPE "
					+ " from g_folder " 
					+ " LEFT OUTER JOIN u_user ON g_folder.CREATE_USER=u_user.ID" 
					+ " WHERE g_folder.NAME LIKE '" + name + "%' AND g_folder.NAME != '"+name+"'" 
					+ " UNION"
					+ " SELECT g_file_relaction.ID,IFNULL(g_file_relaction.FILE_NAME,g_file.FILE_NAME),SIZE,"
					+ " g_file_relaction.CREATE_TIME,"
					+ " CONCAT(g_folder.NAME,IFNULL(g_file_relaction.FILE_NAME,g_file.FILE_NAME)) AS PATH,"
					+ " g_file.CLASS,"
					+ " g_file.EXT_NAME,"
					+ " u_user.NAME AS USER_NAME,u_user.ID AS USER_ID,'1' AS FILE_TYPE"
					+ " FROM g_file_relaction"
					+ " LEFT OUTER JOIN g_folder ON g_file_relaction.FOLDER_ID=g_folder.ID"
					+ " LEFT OUTER JOIN g_file ON g_file_relaction.FILE_ID=g_file.ID"
					+ " LEFT OUTER JOIN u_user ON g_file_relaction.USER_ID=u_user.ID" 
					+ " WHERE g_file_relaction.FOLDER_ID='"+id+"') AS B1 ORDER BY CONVERT(NAME USING gbk)");
			
			
			DataTable dt = SqlSessionManager.getDataTable(sql);
			DataTable dtBack=dt.clone(false);
	
			if (dt.getRowCount() > 0) {
	
				String[] cArr;
				String cName;
				for (DataRow row : dt.getRows()) {
					// 处理字符串，用于判断是否是父路径
					if(row.getString("FILE_TYPE").equals("0")){
						cName = row.getString("Path").replaceFirst(name, "");
						cArr = cName.split("/");
						if (cArr.length == 1) {
							dtBack.addRow(row);
						}
					}
					else {
						dtBack.addRow(row);
					}
					
				}
				if(dtBack.getRowCount() >0){
					for (DataRow dr : dtBack) {
						VFileObject vO = new VFileObject();
						JSONObject dd = dr.toJSONObject();
						vO.setId(dd.has("ID")?dr.getString("ID"):"");
						vO.setFolderName(dd.has("NAME")?dr.getString("NAME"):"");
						vO.setSize(dd.has("SIZE")?dr.getLong("SIZE"):0);
						vO.setCreateTime(dd.has("CREATE_TIME")?
								DateUtil.dateTrans(dr.getDate("CREATE_TIME").toString(),DateUtil.YYYY_MM_DD_HH_MM):"");
						vO.setFileName(dd.has("PATH")?dr.getString("PATH"):"");
						vO.setClassS(dd.has("CLASS")?dr.getString("CLASS"):"");
						vO.setExtName(dd.has("EXT_NAME")?dr.getString("EXT_NAME"):"");
						vO.setUserName(dd.has("USER_NAME")?dr.getString("USER_NAME"):"");
						vO.setUserId(dd.has("USER_ID")?dr.getString("USER_ID"):"");
						vO.setFileType(dd.has("FILE_TYPE")?dr.getString("FILE_TYPE"):"");
						vfList.add(vO);
					}
				}
				return vfList;
			}
	
			return vfList;
		}catch(Exception e){
			LoggerHelper.error(logger, e, "");
			return null;
		}
	}
	
	/**
	 * 获取文件信息json
	 * 
	 * @param path
	 * @param action
	 *        读取数据的动作指令
	 * 
	 * @return
	 * @throws UnsupportedEncodingException 
	 * @throws Exception
	 */
	public List<VFileObject> getFolder(String path, String action) throws UnsupportedEncodingException {
		path = URLDecoder.decode(path, "utf-8");
		String[] cArr = path.split("/");
		String id = cArr[0].toString();
		path = path.replaceFirst(id, "");

		// 下面这个不要语句不和用户绑定

		if (action == null)
			action = "";
		
		
		return getFolder(path);
	
	}
	
	/**
	 * 传入一个文件信息的dt，转换成输出到客户端的json
	 * 
	 * @return 客户端的json
	 * @throws Exception
	 */
	public String getFilePathJson(List<VFileObject> vfList, String path)  {
		try {
			JSONObject json = new JSONObject();
			 SimpleDateFormat sdf =   new SimpleDateFormat( "yyyy-MM-dd HH:mm" );
			 Calendar calendar = Calendar.getInstance();
			if (vfList!=null && vfList.size() > 0) {

				String[] arrExt;
				String name, extensions;
				int i=0;
				int ii=111111;
				int j=0;
				for (VFileObject row : vfList) {
					JSONObject fileInfo = new JSONObject();
					fileInfo.put("ID", row.getId());
					fileInfo.put("Path", row.getId() + CebaFileManageUtil.filterJsonName(row.getFileName()));
					name= row.getFolderName();
//					fileInfo.put("Filename", CebaFileManageUtil.filterJsonName(name));
					fileInfo.put("Filename", name);
					if(row.getFileType().equals("0")){
						extensions = "dir";

						fileInfo.put("File Type", extensions);
						fileInfo.put("Preview", CebaFileManageUtil.getFileExtensionsImg(extensions));
						
						fileInfo.put("treePreview", "directory");
						fileInfo.put("Error", "");
						fileInfo.put("Index", ii++);
						
						JSONObject properties = new JSONObject();
						fileInfo.put("Properties", properties);
						properties.put("Date Modified", row.getCreateTime());
						calendar.setTime(sdf.parse(row.getCreateTime()));
						properties.put("filemtime", calendar.getTime());
						fileInfo.put("Code", "");
					}
					else{
						arrExt = name.split("\\.");
						extensions = arrExt[arrExt.length - 1];
						fileInfo.put("File Type", extensions);

						if (row.getClassS().equals("sign")) {
							fileInfo.put("Preview", CebaFileManageUtil.getFileExtensionsImg("sign"));
							fileInfo.put("treePreview", "pdfsign");
						} else {
							fileInfo.put("Preview", CebaFileManageUtil.getFileExtensionsImg(extensions));
							fileInfo.put("treePreview", extensions);
						}
									
						fileInfo.put("Error", "");
						fileInfo.put("Index", i++);

						JSONObject properties = new JSONObject();
						properties.put("Size", Double.valueOf(row.getSize()));
						properties.put("Date Modified", row.getCreateTime());
						calendar.setTime(sdf.parse(row.getCreateTime()));
						properties.put("filemtime", calendar.getTime());
						fileInfo.put("Properties", properties);
						fileInfo.put("Code", "");
					}
					json.put(j+"", fileInfo);
					j++;

				}
			}
				
			return CebaFileManageUtil.sortJSON2String(json);
		} catch (Exception e) {
			LoggerHelper.error(logger, e, "");
			return "{}";
		}
		

	}
	
	/**
	 * 根据目录路径获取目录ID
	 */
	public String getRelationFolderIdByPath(String path){
		Sql sql = new Sql("SELECT RELATION_FOLDER FROM g_folder WHERE NAME=?");
		sql.addParameter("NAME", path);
		return SqlSessionManager.getFieldStringValue(sql);
	}
	
	/**
	 * 把一个目录添加到关联目录表中
	 * 
	 * @param folderID
	 * @param json
	 *            原文件夹的目录结构
	 * @return
	 * @throws Exception
	 */
	public JSONObject addRelationFolder(String folderID, JSONObject json){

		try {
			Sql sql = new Sql(
					"SELECT ID,NAME,'' AS SIZE,CREATE_TIME,'0' AS FileType,NAME AS Path,IMG from g_folder WHERE ID =?");
			sql.addParameter("ID", folderID);

			DataTable dt = SqlSessionManager.getDataTable(sql);

			String name, extensions;
			String[] arr;
			for (DataRow row : dt.getRows()) {

				JSONObject fileInfo = new JSONObject();
				fileInfo.put("ID", row.getString("ID"));
				fileInfo.put("Path", row.getString("ID") + row.getString("NAME"));
				arr = row.getString("NAME").split("/");

				name = arr[arr.length - 1];
				fileInfo.put("Filename", name);

				extensions = "dir";
				fileInfo.put("File Type", extensions);

				fileInfo.put("Preview", CebaFileManageUtil.getFileExtensionsImg("locked__Open"));
				fileInfo.put("treePreview", "directory-locked");
				fileInfo.put("Error", "");
				fileInfo.put("Index", "98");
				JSONObject properties = new JSONObject();
				fileInfo.put("Properties", properties);
				properties.put("Date Modified", row.getString("CREATE_TIME"));
				fileInfo.put("Code", "");
				json.put(row.getString("NAME"), fileInfo);
			}

			return json;
		} catch (JSONException e) {
			LoggerHelper.error(logger, e, "");
			return json;
		}
	}
	
	

	/**
	 * 查询，全文和目录检索
	 * 
	 * @param path
	 * @param key
	 *            查询关键字
	 * 
	 * @return
	 * @throws Exception
	 */
	public String getFullTextSearchFolder(String path, String key)  {
		JSONObject json = new JSONObject();
		try {
			path = URLDecoder.decode(path, "utf-8");
			String[] cArr = path.split("/");
			String id = cArr[0].toString();
			String fmPath = path.replaceFirst(id, "");
			
			//先搜索目录
			DataTable dtFolders=searchFMFolder(fmPath, key, false);
			
			//获取目录json
			if (dtFolders != null && dtFolders.getRowCount() > 0) {
				for (DataRow row : dtFolders.getRows()) {
					JSONObject fileInfo = new JSONObject();
					fileInfo.put("ID", row.getString("ID"));
					fileInfo.put("Path", row.getString("ID") + row.getString("NAME"));
					fileInfo.put("Filename", row.getString("FOLDER_NAME"));

					fileInfo.put("File Type", "dir");
					fileInfo.put("Preview", CebaFileManageUtil.getFileExtensionsImg("dir"));
					fileInfo.put("treePreview",
							!row.getString("IMG").equals("") ? row.getString("IMG") : "directory");
					fileInfo.put("Error", "");
					if (row.getString("CLASS").equals("net")) {
						fileInfo.put("Index", "99");
					} else {
						fileInfo.put("Index", "11");
					}
					JSONObject properties = new JSONObject();
					fileInfo.put("Properties", properties);
					properties.put("Date Modified", row.getString("CREATE_TIME"));
					properties.put("filemtime", row.getDate("CREATE_TIME").getTime());
					fileInfo.put("Code", "");
					json.put(row.getString("NAME"), fileInfo);
				}
			}
			
			DataTable dtFiles=searchFMFilesInFolder(fmPath, key, false);
			
			if (dtFiles != null && dtFiles.getRowCount() > 0) {
				for (DataRow row : dtFiles.getRows()) {
					JSONObject fileInfo = new JSONObject();
					fileInfo.put("ID", row.getString("ID"));
					fileInfo.put("Path",row.getString("ID")+row.getString("PATH"));
					fileInfo.put("Filename", row.getString("FILE_NAME"));
					
					String extensions =  row.getString("EXT_NAME");
					fileInfo.put("File Type", extensions);

					fileInfo.put("Preview", CebaFileManageUtil.getFileExtensionsImg(extensions));
					fileInfo.put("treePreview", extensions);
					fileInfo.put("Error", "");
					fileInfo.put("Index", "0");

					JSONObject properties = new JSONObject();
					properties.put("Size", row.getDouble("SIZE"));
					properties.put("Date Modified", row.getString("CREATE_TIME"));
					properties.put("filemtime", row.getDate("CREATE_TIME").getTime());
					fileInfo.put("Properties", properties);
					fileInfo.put("Code", "");
					json.put(row.getString("PATH"), fileInfo);
				}
			}
			
			return CebaFileManageUtil.sortJSON2String(json);
		} catch (Exception e) {
			LoggerHelper.error(logger, e, "");
			return "{}";
		}
	}
	
	/**
	 * 根据ID获取文件或目录的信息
	 * 
	 * @param id
	 * @return
	 * @
	 */
	public VFileObject getFileInfo(String id,String path){
		try {
			VFileObject vO = new VFileObject();
			
			GFileRelaction gfr =  getGFileRelactionById(id);
			// 先检查文件目录
			if (gfr == null) {
				GFolder gf = getGFolderByIdAndFields(id,
						"ID,PID AS FOLDER_ID,NAME AS FILE_NAME,IFNULL(CREATE_TIME,now()) AS CREATE_TIME,"
						+ " '' AS FILE_PATH,'0' AS TYPE,'0' AS SIZE,CLASS ",path);
				if (gf != null){
					copyGFolderToVFile(gf, vO);
					if(StringUtil.isEmptyString(gf.getId())){
						String pid= getFolderFieldValueByFolderPath("ID"," NAME='"+CebaFileManageUtil.getFmParentPath(gf.getFileName())+"'");
						if(!pid.equals("")){
							vO.setId(pid);
						}
					}
				}
			}else{
				copyGFileRelactionToVFile(gfr,vO);
			}
			return vO;
		} catch (Exception e) {
			LoggerHelper.error(logger, e, "");
		}
		return null;
	}	

	/**
	 * 根据ID获取文件
	 * 
	 * @param id
	 * @return
	 * @
	 */
	public GFileRelaction getGFileRelactionById(String id){

		try {
			DataTable dt = SqlSessionManager.getDataTable(
					"SELECT g_file_relaction.ID,g_file_relaction.FOLDER_ID,"
							+ "	IFNULL(g_file_relaction.FILE_NAME,g_file.FILE_NAME) AS FILE_NAME,"
							+ " g_file.VIRTUAL_PATH,g_file.ID AS FILE_ID,"
							+ "  IFNULL(g_file.CREATE_TIME,now()) AS CREATE_TIME,g_file.FILE_PATH,'1' AS TYPE,"
							+ "	g_file.SIZE,g_file.CLASS,g_file_relaction.ITEM_INDEX,g_file_relaction.RFLAG "
							+ " FROM g_file_relaction "
							+ " LEFT OUTER JOIN g_folder ON g_file_relaction.FOLDER_ID=g_folder.ID"
							+ " LEFT OUTER JOIN g_file ON g_file_relaction.FILE_ID=g_file.ID"
							+ " WHERE g_file_relaction.ID='" + id + "'");
			if(dt !=null && dt.getRowCount() >0){
				GFileRelaction gfr = new GFileRelaction();
				copyDrToGFileRelaction(dt.getRow(0), gfr);
				return gfr;
			}
		} catch (Exception e) {
			LoggerHelper.error(logger, e, "");
		}
		return null;
	}

	/**
	 * 获取目录下面的所有目录
	 * 
	 * @param fmPath
	 *            查询的目录
	 * @param key
	 *            默认为""，获取的内容检索关键字，目前只检索名字和内容
	 * @param bRelation
	 *            默认为false，是否检索关联目录（目录下面有关联目录和关联sql语句，都包含在里面）                  
	 * @return
	 * @
	 */
	public DataTable searchFMFolder(String fmPath,String key,Boolean bRelation)  {
		
		try {
			if(bRelation){
				DataTable dt=null;
				if(key.equals("") || key==null){
					//第一步获取本目录的文件夹
					DataTable dtAll=SqlSessionManager.getDataTable("SELECT * FROM g_folder WHERE NAME LIKE '" + fmPath + "%'");
					dt=dtAll.clone(true);
					for (DataRow row : dtAll.getRows()) {
						//第二步获取管理目录下面的所有目录名
						if(!row.getString("RELATION_FOLDER").equals("")){
							String[] arr = row.getString("RELATION_FOLDER").split(";");
							for (int i = 0; i < arr.length; i++) {
								if (!arr[i].equals("")) {
									String folderPath=SqlSessionManager.getFieldStringValue("SELECT NAME FROM g_folder WHERE ID='"+arr[i]+"'");
									if(!folderPath.equals("")){
										DataTable dtRel=searchFMFolder(folderPath,"", false);
										if(dtRel!=null && dtRel.getRowCount()>0){
											dt.getRows().addAll(dtRel.getRows());
										}
									}
								}
							}						
						}
					}
				}
				else{
					dt=searchFMFolder(fmPath,key,false);
					
					DataTable dtAll=SqlSessionManager.getDataTable("SELECT * FROM g_folder WHERE NAME LIKE '" + fmPath + "%'");
					for (DataRow row : dtAll.getRows()) {
						//第二步获取管理目录下面的所有目录名
						if(!row.getString("RELATION_FOLDER").equals("")){
							String[] arr = row.getString("RELATION_FOLDER").split(";");
							for (int i = 0; i < arr.length; i++) {
								if (!arr[i].equals("")) {
									String folderPath=SqlSessionManager.getFieldStringValue("SELECT NAME FROM g_folder WHERE ID='"+arr[i]+"'");
									if(!folderPath.equals("")){
										DataTable dtRel=searchFMFolder(folderPath,key, false);
										if(dtRel!=null && dtRel.getRowCount()>0){
											dt.getRows().addAll(dtRel.getRows());
										}
									}
								}
							}			
						}
					}
				}
				//？这个地方加一个去除重复项
					
				return dt;
			}
			else{
				if(key.equals("") || key==null){
					return SqlSessionManager.getDataTable("SELECT * FROM g_folder WHERE NAME LIKE '" + fmPath + "%'");
				}
				else{
					String tj = "";
					String[] arr = key.split(" ");
					for (String s : arr) {
						if (!s.equals("")) {
							//这里使用OR而不是AND是因为目录名不需要进一步排除，只需要包容
							tj += "  FOLDER_NAME LIKE '%" + s+ "%' OR";
						}
					}
					tj=tj.substring(0, tj.length()-2);
					
					return SqlSessionManager.getDataTable("SELECT * FROM g_folder WHERE (NAME LIKE '" + fmPath + "%') AND (" + tj + ")");
				}
			}
		} catch (Exception e) {
			LoggerHelper.error(logger, e, "");
			return null;
		}

	}
	
	/**
	 * 获取一个FM目录下的所有目录结构
	 * @param fmPathOrId 目录路径或目录Id
	 * @param key 查询的关键字
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public List<VFileObject> getFMFoldersList(String fmPathOrId,String key)  {
		List<VFileObject> vfList= new ArrayList();
		try {
			if(fmPathOrId==null || fmPathOrId.equals("")){
				return null;
			}
			String fmPath="";
			Sql sql=new Sql("SELECT ID,NAME FROM g_folder WHERE ID=? OR NAME=?");
			sql.addParameter("ID", fmPathOrId);
			sql.addParameter("NAME", fmPathOrId);
			
			DataTable dtFolder=SqlSessionManager.getDataTable(sql);
			if(dtFolder!=null && dtFolder.getRowCount()>0){
				fmPath=dtFolder.getRow(0).getString("NAME");
			}
			
			if(StringUtil.isEmptyString(key)){
				DataTable dt = SqlSessionManager.getDataTable("SELECT * FROM g_folder WHERE NAME LIKE '" + fmPath + "%'");
				if( dt != null && dt.getRowCount() >0){
					for(DataRow dr:dt){
						VFileObject vf = new VFileObject();
						copyGFolderDataRowToVFileObject(dr, vf);
						vfList.add(vf);
					}
				}
				return vfList;
			}
			else{
				String tj = "";
				String[] arr = key.split(" ");
				for (String s : arr) {
					if (!s.equals("")) {
						//这里使用OR而不是AND是因为目录名不需要进一步排除，只需要包容
						tj += "  FOLDER_NAME LIKE '%" + s+ "%' OR";
					}
				}
				tj=tj.substring(0, tj.length()-2);
				DataTable dt = SqlSessionManager.getDataTable("SELECT * FROM g_folder WHERE (NAME LIKE '" + fmPath + "%') AND (" + tj + ")");
				if( dt != null && dt.getRowCount() >0){
					for(DataRow dr:dt){
						VFileObject vf = new VFileObject();
						copyGFolderDataRowToVFileObject(dr, vf);
						vfList.add(vf);
					}
				}
				return vfList;
			}
		} catch (Exception e) {
			LoggerHelper.error(logger, e, "");
			return null;
		}
	}
	
	
	/**
	 * 获取一个FM目录下的所有文件列表
	 * @param folderId
	 * @param key 查询的关键字
	 * @return
	 */
	public List<VFileObject> getFMFilesListByFolderId(String folderId,String key)  {
			
		try {
			if(StringUtil.isEmptyString(folderId)){
				return null;
			}
			String fmPath="";
			Sql sql=new Sql("SELECT NAME FROM g_folder WHERE ID=?");
			sql.addParameter("ID", folderId);
			
			DataTable dtFolder=SqlSessionManager.getDataTable(sql);
			if(dtFolder!=null && dtFolder.getRowCount()>0){
				fmPath=dtFolder.getRow(0).getString("NAME");
			}
			
			return getFMFilesListByFolderPath(fmPath,"");
		} catch (Exception e) {
			LoggerHelper.error(logger, e, "");
			return null;
		}
	}
	
	/**
	 * 获取一个FM目录下的所有文件列表
	 * @param folderPath 目录路径
	 * @param key 查询的关键字
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public List<VFileObject> getFMFilesListByFolderPath(String folderPath,String key)  {
		List<VFileObject> vfList= new ArrayList();
		try {
			if(folderPath==null || folderPath.equals("")){
				return null;
			}
			
			if(key.equals("") || key==null){
				DataTable dt = SqlSessionManager.getDataTable("SELECT g_file.*,g_file_relaction.ID AS RELATION_FILE_ID,"
						+ "g_file_relaction.FILE_NAME AS RELATION_FILE_NAME,g_file_relaction.FOLDER_ID "
						+ " FROM g_file_relaction  LEFT OUTER JOIN g_file ON g_file.ID=g_file_relaction.FILE_ID "
						+ " WHERE g_file_relaction.FOLDER_ID IN (SELECT ID FROM g_folder WHERE NAME LIKE '"+folderPath+"%')");
				
				if( dt != null && dt.getRowCount() >0){
					for(DataRow dr:dt){
						VFileObject vf = new VFileObject();
						copyGFileDataRowToVFileObject(dr, vf);
						vf.setFileRelactionId(dr.getString("RELATION_FILE_ID"));
						vf.setFileRelactionName(dr.getString("RELATION_FILE_NAME"));
						vf.setFolderId(dr.getString("FOLDER_ID"));
						vfList.add(vf);
					}
				}
				return vfList;
			}
			else{
				String tj = "";
				String[] arr = key.split(" ");
				for (String s : arr) {
					if (!s.equals("")) {
						//这里使用OR而不是AND是因为目录名不需要进一步排除，只需要包容
						tj += "  g_file_relaction.FILE_NAME LIKE '%" + s+ "%' OR";
					}
				}
				tj=tj.substring(0, tj.length()-2);
				
				DataTable dt = SqlSessionManager.getDataTable("SELECT g_file.*,g_file_relaction.ID AS RELATION_FILE_ID,"
						+ "g_file_relaction.FILE_NAME AS RELATION_FILE_NAME,g_file_relaction.FOLDER_ID "
						+ " FROM g_file_relaction  LEFT OUTER JOIN g_file ON g_file.ID=g_file_relaction.FILE_ID "
						+ " WHERE g_file_relaction.FOLDER_ID IN (SELECT ID FROM g_folder WHERE NAME LIKE '"+folderPath+"%') AND (" + tj + ")");
				if( dt != null && dt.getRowCount() >0){
					for(DataRow dr:dt){
						VFileObject vf = new VFileObject();
						copyGFileDataRowToVFileObject(dr, vf);
						vf.setFileRelactionId(dr.getString("RELATION_FILE_ID"));
						vf.setFileRelactionName(dr.getString("RELATION_FILE_NAME"));
						vf.setFolderId(dr.getString("FOLDER_ID"));
						vfList.add(vf);
					}
				}
				return vfList;
			}
		} catch (Exception e) {
			LoggerHelper.error(logger, e, "");
			return null;
		}
	
	}
	
	/**
	 * 根据传过来的JSON获取所有的文件
	 * @param filesJson 文件json,包含文件Id或文件包Id
	 */
	public List<VFileObject> getFMFilesByJson(String filesJson)  {
		try {
			JSONArray json=new JSONArray (filesJson);		
			List<VFileObject> backList = null; 
			List<VFileObject> fileList = null; 
			for(int i=0;i<json.length();i++){  
				 JSONObject j =json.getJSONObject(i);  
				 fileList= null; 
				 if(j.getString("type").equals("dir")){
					fileList = getFMFilesListByFolderId(j.getString("id"),"");
				 }
				 else {
					fileList = getFileInfosById(j.getString("id"));
				 }
				 if(backList == null){
					backList = new ArrayList<VFileObject>();
				 }
				 if(fileList!=null && fileList.size()>0){
					 if(backList!=null){
						 backList.addAll(fileList);
					 }
				 }
			}
			
			return backList;
		} catch ( Exception e) {
			LoggerHelper.error(logger, e, "");
			return null;
		}
	}
	
	/**
	 * 搜索目录下面的所有文件，这里获取的是FM的关联文件
	 * 
	 * @param fmPath
	 *            查询的目录
	* @param key 关键字
	 *                  
	 * @return
	 * @
	 */
	public DataTable searchFMFilesInFolder(String fmPath,String key,Boolean bRelation)  {
		try {
			if(bRelation){
				DataTable dt=SqlSessionManager.getDataTable("SELECT *,'' AS PATH,'' AS FILE_PATH,'' AS EXT_NAME,"
						+ "'' AS VIRTUAL_PATH,'' AS TEXT_CONTENT,'' AS SIZE FROM g_file_relaction WHERE 1<>1");
				
				if(key.equals("") || key==null){
					//第一步获取本目录下所有关联文件
					DataTable dtFolders=searchFMFolder(fmPath,"", true);
					for (DataRow row : dtFolders.getRows()) {
						//第二步获取这个目录下的所有关联文件
						DataTable dtRelFiles= SqlSessionManager.getDataTable("SELECT g_file_relaction.*,"
								+ "CONCAT(g_folder.NAME,IFNULL(g_file_relaction.FILE_NAME,g_file.FILE_NAME)) AS PATH,"
								+ " g_file.FILE_PATH,g_file.EXT_NAME,g_file.VIRTUAL_PATH,g_file.TEXT_CONTENT,g_file.SIZE " 
								+ " FROM g_file_relaction "
								+ " LEFT OUTER JOIN g_folder ON g_file_relaction.FOLDER_ID=g_folder.ID "
								+ " LEFT OUTER JOIN g_file ON g_file_relaction.FILE_ID=g_file.ID " 
								+ " WHERE (g_folder.ID = '" + row.getString("ID") + "') ");
						if(dtRelFiles!=null && dtRelFiles.getRowCount()>0){
							dt.getRows().addAll(dtRelFiles.getRows());
						}
						
						
						//获取关联的sql语句的文件
						if(!row.getString("READ_SQL").equals("")){
							DataTable dtReadSql=SqlSessionManager.getDataTable(row.getString("READ_SQL"));
							if(dtReadSql!=null && dtReadSql.getRowCount()>0){
								String tj=" g_file_relaction.ID IN (";
								for (DataRow rowRS : dtReadSql.getRows()) {
									tj+="'"+rowRS.getString("ID")+"',";
								}
								tj+="'0')";
								
								DataTable dt1=SqlSessionManager.getDataTable("SELECT g_file_relaction.*,"
										+ " CONCAT(g_folder.NAME,IFNULL(g_file_relaction.FILE_NAME,g_file.FILE_NAME)) AS PATH,"
										+ " g_file.FILE_PATH,g_file.EXT_NAME,g_file.VIRTUAL_PATH,g_file.TEXT_CONTENT,g_file.SIZE " 
										+ " FROM g_file_relaction "
										+ " LEFT OUTER JOIN g_folder ON g_file_relaction.FOLDER_ID=g_folder.ID "
										+ " LEFT OUTER JOIN g_file ON g_file_relaction.FILE_ID=g_file.ID " 
										+ " WHERE " + tj);
								if(dt1!=null && dt1.getRowCount()>0){
									dt.getRows().addAll(dt1.getRows());
								}
							}
						}
					}
				}else {
					//第一步获取本目录下所有关联文件
					
					String tj = "";
					String[] arr = key.split(" ");
					for (String s : arr) {
						if (!s.equals("")) {
							tj += " AND (IFNULL(g_file_relaction.FILE_NAME,g_file.FILE_NAME) LIKE '%" + s
									+ "%' OR g_file.TEXT_CONTENT LIKE '%" + s + "%')";
						}
					}

					DataTable dtFolders=searchFMFolder(fmPath,"", true);
					for (DataRow row : dtFolders.getRows()) {
						//第二步获取这个目录下的所有关联文件
						DataTable dtRelFiles= SqlSessionManager.getDataTable("SELECT g_file_relaction.*,"
								+ " CONCAT(g_folder.NAME,IFNULL(g_file_relaction.FILE_NAME,g_file.FILE_NAME)) AS PATH,"
								+ " g_file.FILE_PATH,g_file.EXT_NAME,g_file.VIRTUAL_PATH,g_file.TEXT_CONTENT,g_file.SIZE " 
								+ " FROM g_file_relaction "
								+ " LEFT OUTER JOIN g_folder ON g_file_relaction.FOLDER_ID=g_folder.ID "
								+ " LEFT OUTER JOIN g_file ON g_file_relaction.FILE_ID=g_file.ID " 
								+ " WHERE (g_folder.ID = '" + row.getString("ID") + "') " + tj);
						if(dtRelFiles!=null && dtRelFiles.getRowCount()>0){
							dt.getRows().addAll(dtRelFiles.getRows());
						}
						
						
						//获取关联的sql语句的文件
						if(!row.getString("READ_SQL").equals("")){
							DataTable dtReadSql=SqlSessionManager.getDataTable(row.getString("READ_SQL"));
							if(dtReadSql!=null && dtReadSql.getRowCount()>0){
								String tj1=" g_file_relaction.ID IN (";
								for (DataRow rowRS : dtReadSql.getRows()) {
									tj1+="'"+rowRS.getString("ID")+"',";
								}
								tj1+="'0')";
								Sql keySql = new Sql("SELECT g_file_relaction.*,"
										+ " CONCAT(g_folder.NAME,IFNULL(g_file_relaction.FILE_NAME,g_file.FILE_NAME)) AS PATH,"
										+ " g_file.FILE_PATH,g_file.EXT_NAME,g_file.VIRTUAL_PATH,g_file.TEXT_CONTENT,g_file.SIZE "
										+ " FROM g_file_relaction "
										+ " LEFT OUTER JOIN g_folder ON g_file_relaction.FOLDER_ID=g_folder.ID "
										+ " LEFT OUTER JOIN g_file ON g_file_relaction.FILE_ID=g_file.ID "
										+ " WHERE (" + tj1 +") " + tj);
								DataTable dt1=SqlSessionManager.getDataTable(keySql);
								if(dt1!=null && dt1.getRowCount()>0){
									dt.getRows().addAll(dt1.getRows());
								}
							}
						}
					}
				}
				
				
				//？排除重复文件
				
						
				return dt;
			}
			else{
				if(key.equals("") || key==null){
					return SqlSessionManager.getDataTable("SELECT g_file_relaction.*,CONCAT(g_folder.NAME,IFNULL(g_file_relaction.FILE_NAME,g_file.FILE_NAME)) AS PATH,"
							+ " g_file.FILE_PATH,g_file.EXT_NAME,g_file.VIRTUAL_PATH,g_file.TEXT_CONTENT,g_file.SIZE " 
							+ " FROM g_file_relaction "
							+ " LEFT OUTER JOIN g_folder ON g_file_relaction.FOLDER_ID=g_folder.ID "
							+ " LEFT OUTER JOIN g_file ON g_file_relaction.FILE_ID=g_file.ID " 
							+ " WHERE g_folder.NAME LIKE '"
							+ fmPath + "%'");
				}
				else{
					String tj = "";
					String[] arr = key.split(" ");
					for (String s : arr) {
						if (!s.equals("")) {
							tj += " AND (IFNULL(g_file_relaction.FILE_NAME,g_file.FILE_NAME) LIKE '%" + s
									+ "%' OR g_file.TEXT_CONTENT LIKE '%" + s + "%')";
						}
					}

					Sql sql = new Sql("SELECT g_file_relaction.*,CONCAT(g_folder.NAME,IFNULL(g_file_relaction.FILE_NAME,g_file.FILE_NAME)) AS PATH,"
							+ " g_file.FILE_PATH,g_file.EXT_NAME,g_file.VIRTUAL_PATH,g_file.TEXT_CONTENT,g_file.SIZE "
							+ " FROM g_file_relaction "
							+ " LEFT OUTER JOIN g_folder ON g_file_relaction.FOLDER_ID=g_folder.ID "
							+ " LEFT OUTER JOIN g_file ON g_file_relaction.FILE_ID=g_file.ID "
							+ " WHERE (g_folder.NAME LIKE '" + fmPath + "%') " + tj);
					return SqlSessionManager.getDataTable(sql);
				}
				
			}
		} catch (Exception e) {
			LoggerHelper.error(logger, e, "");
			return null;
		}

	}
	
	/**
	 * 删除一个文件夹里面所有的内容
	 * 
	 * @param fmPath
	 *            删除目录
	 * @return
	 * @
	 */
	public Boolean deleteFolder(String fmPath)  {

		try {
			DataTable dtFiles = null;
			DataTable dtFolders = null;
			dtFiles = searchFMFilesInFolder(fmPath,"",false);
			dtFiles.getColumn("ID").setPrimaryKey(true);

			dtFolders = searchFMFolder(fmPath,"",false);
			dtFolders.getColumn("ID").setPrimaryKey(true);
		

			DataTableSqlBuilder sqlBuilder1 = new DataTableSqlBuilder(dtFiles);
			SqlDataSource sqlDataSource1 = sqlBuilder1.toDataSource(DBAction.Delete);
			Result result1 = new Result();
			sqlDataSource1.delete(result1);

			DataTableSqlBuilder sqlBuilder = new DataTableSqlBuilder(dtFolders);
			SqlDataSource sqlDataSource = sqlBuilder.toDataSource(DBAction.Delete);
			Result result = new Result(true);
			sqlDataSource.delete(result);

			if (result.isSucceed()) {
				return true;
			}

			return false;
		} catch (Exception e) {
			LoggerHelper.error(logger, e, "");
			return false;
		}

	}
	
	/**
	 * 删除一个Fm关联文件
	 * 
	 * @param relationId
	 *            删除目录
	 * @return
	 * @
	 */
	public Boolean deleteFmFile(String relationId) {
		try {
			Sql sql=new Sql("DELETE FROM g_file_relaction WHERE ID=?");
			sql.addParameter("ID", relationId);
			
			IStore store = StoreManager.create("g_file_relaction");
			IObject object = store.get(relationId);
			store = StoreManager.create("g_file_relaction_delete");
			
			if (SqlSessionManager.execute(sql)) {
				store.insert(object);
				return true;
			}
			return false;
		} catch (Exception e) {
			LoggerHelper.error(logger, e, "");
			return false;
		}
	}
	
	/**
	 * 删除一组文件，文件也可以是文件夹
	 * @param filesJson 文件json
	 * @return
	 * @
	 */
	public Boolean deleteFiles(String filesJson)  {
		 try {
			JSONArray json=new JSONArray (filesJson);
			 for(int i=0;i<json.length();i++){  
				 JSONObject j =json.getJSONObject(i);  
				 if(j.getString("type").equals("dir")){
					 String fmPath=SqlSessionManager.getFieldStringValue("SELECT NAME FROM g_folder WHERE ID='"+j.getString("id")+"'");
					 if(!fmPath.equals("")){
						 deleteFolder(fmPath);
					 }
					 
				 }
				 else {
					   deleteFmFile(j.getString("id"));
				 }
			  }  
			 return true;
		} catch (JSONException e) {
			LoggerHelper.error(logger, e, "");
			return false;
		}
	}
	
	/**
	 * 删除物理路径文件
	 * @param fileId 各种关联文件ID；
	 * @return
	 */
	public Boolean deletePhysicalFile(String fileId)  {
		try {
			GFile gFile =  getFilePath(fileId);
			if(gFile !=null){
				String path = gFile.getFilePath();
				if(FileHelper.exists(path)){
					if(FileHelper.deleteFile(path)){
						return true;
					}
				}
			}
			return false;
		} catch (Exception e) {
			LoggerHelper.error(logger, e, "");
			return false;
		}
	}

	/**
	 * 文件夹是否存在,要特定用户
	 * 
	 * @param path
	 *            目录路径
	 * @return
	 * @
	 */
	public boolean existDirByUser(String path,String userId){
		boolean b = false;
		try {

			if (SqlSessionManager.getFieldLongValue(
					"SELECT COUNT(ID) AS C from  g_folder WHERE NAME = '" + path + "' AND  USER_ID='" 
								+ userId + "'") > 0) {
				b = true;
			}
			return b;
		} catch (Exception e) {
			LoggerHelper.error(logger, e, "");
			return b;
		}
	}
	

	/**
	 * 文件夹下面是否存在子文件
	 * 
	 * @param id
	 * @return
	 * @
	 */
	public boolean existChildFile(String id,String userId)  {

		boolean b = false;
		try {

			if (SqlSessionManager.getFieldLongValue("SELECT COUNT(ID) AS C from  g_file_relaction WHERE FOLDER_ID='" + id
					+ "' AND CREATE_USER='" + userId + "'") > 0) {
				b = true;
			}
			return b;
		} catch (Exception e) {
			LoggerHelper.error(logger, e, "");
			return b;
		}
	}
	
	/**
	 * 文件夹下面是否存在子文件夹
	 * 
	 * @param path
	 *            目录路径
	 * @return
	 * @
	 */
	public boolean existChildDir(String path ,String userId)  {
		boolean b = false;
		try {

			if (SqlSessionManager.getFieldLongValue("SELECT COUNT(ID) AS C from  g_folder WHERE NAME != '" + path
					+ "' AND NAME LIKE '" + path + "%' AND USER_ID='" + userId + "'") > 0) {
				b = true;
			}
			return b;
		} catch (Exception e) {
			LoggerHelper.error(logger, e, "");
			return b;
		}
	}
	

	/**
	 * 文件夹是否存在
	 * 
	 * @param path
	 *            目录路径
	 * @return
	 * @
	 */
	public boolean existDir(String path)  {
		boolean b = false;
		try {
			if (SqlSessionManager.getFieldLongValue("SELECT COUNT(ID) AS C from  g_folder WHERE NAME = '" + path + "'") > 0) {
				b = true;
			}
			return b;
		} catch (Exception e) {
			LoggerHelper.error(logger, e, "");
			return b;
		}
	}
	
	/**
	 * 获取复制到目录结构
	 * 
	 * @param path
	 * @return
	 * @
	 */

	public String getCopyFolderList(String path)  {

		try {
			String homePage = ResourceUtils.getMessage("IDS_HOMEPAGE");
			Sql sql = new Sql("SELECT ID,REPLACE(NAME,'"+path+"','"+homePage+"/') AS NAME from g_folder "
					+ " WHERE NAME LIKE '"+path+"%'  ORDER BY NAME ");

			DataTable dt = SqlSessionManager.getDataTable(sql);

			return dt.toJSONObjectString();
		} catch (Exception e) {
			LoggerHelper.error(logger, e, "");
			return DBJSONHelper.getEmptyDBJSONString();
		}
	}
	
	/**
	 * 给当前目录加一个当日目录
	 * 
	 * @param path
	 *            目录路径
	 * @return
	 * @
	 */
	public boolean addDateDir(String path,String userId)  {
		boolean b = false;
		try {
			//path = path + "/" + DateUtils.formatDate(new Date()) + "/";
			path = path + "/";
			if (!existDirByUser(path,userId)) {
				Sql sql = new Sql("insert into g_folder(ID,NAME,USER_ID)values(?,?,?)");
				Parameters parameters = sql.getParameters();
				//
				parameters.add("ID", ID.getGuid());
				parameters.add("NAME", path);
				parameters.add("USER_ID", userId);

				if (!SqlSessionManager.execute(sql)) {
					b = true;
				}
			}
		} catch (Exception e) {
			LoggerHelper.error(logger, e, "");
		}
		return b;
	}

	/**
	 * 有一些默认的文件夹是添加报告目录中
	 * 
	 * @param parentPath
	 *            父级目录路径
	 * @return
	 * @
	 */
	public Boolean addDefalutRelationToReport(String parentPath,String userId)  {

		try {
			Commands cc = new Commands();

			Sql sqlReportTemplate = new Sql("SELECT ID FROM g_folder WHERE USER_ID=? AND CLASS='"+FileClassConstants.REPORTTEMPLATE+"'");
			sqlReportTemplate.addParameter("USER_ID", userId);

			// 自己的报告模板管理
			String tempIds = SqlSessionManager.getFieldStringValue(sqlReportTemplate);

			Sql sql1 = new Sql(
					"insert into g_folder(ID,NAME,FOLDER_NAME,CLASS,USER_ID,CREATE_USER,IMG,RELATION_FOLDER,CREATE_TIME)values(?,?,?,?,?,?,?,?,?)");
			Parameters parameters1 = sql1.getParameters();
			parameters1.add("ID", ID.getGuid());
			parameters1.add("NAME", parentPath + "报告模板/");
			parameters1.add("FOLDER_NAME", "报告模板");
			parameters1.add("CLASS", "net");
			parameters1.add("USER_ID", userId);
			parameters1.add("CREATE_USER", userId);
			parameters1.add("IMG", "net");
			parameters1.add("RELATION_FOLDER", tempIds);
			parameters1.add("CREATE_TIME", new Date());
			cc.add(sql1);

			Sql sqlImage = new Sql(
					"SELECT ID FROM g_folder WHERE CLASS in ('image') AND USER_ID IN (SELECT USER_ID FROM u_privilege WHERE Object_Id in ('101'))");

			DataTable dt = SqlSessionManager.getDataTable(sqlImage);
			tempIds = "";
			for (DataRow row : dt.getRows()) {
				tempIds += row.getString("ID") + ";";
			}

			Sql sql2 = new Sql(
					"insert into g_folder(ID,NAME,FOLDER_NAME,CLASS,USER_ID,CREATE_USER,IMG,RELATION_FOLDER,CREATE_TIME)values(?,?,?,?,?,?,?,?,?)");
			Parameters parameters2 = sql2.getParameters();
			//
			parameters2.add("ID", ID.getGuid());
			parameters2.add("NAME", parentPath + "样品照片/");
			parameters2.add("FOLDER_NAME", "样品照片");
			parameters2.add("CLASS", "net");
			parameters2.add("USER_ID", userId);
			parameters2.add("CREATE_USER", userId);
			parameters2.add("IMG", "net");
			parameters2.add("RELATION_FOLDER", tempIds);
			parameters2.add("CREATE_TIME", new Date());
			cc.add(sql2);

			Sql sqlTest = new Sql(
					"SELECT ID FROM g_folder WHERE CLASS in ('test') AND USER_ID IN (SELECT USER_ID FROM u_privilege WHERE Object_Id in ('102'))");

			dt = SqlSessionManager.getDataTable(sqlTest);
			tempIds = "";
			for (DataRow row : dt.getRows()) {
				tempIds += row.getString("ID") + ";";
			}

			Sql sql3 = new Sql(
					"insert into g_folder(ID,NAME,FOLDER_NAME,CLASS,USER_ID,CREATE_USER,IMG,RELATION_FOLDER,CREATE_TIME)values(?,?,?,?,?,?,?,?,?)");
			Parameters parameters3 = sql3.getParameters();
			//
			parameters3.add("ID", ID.getGuid());
			parameters3.add("NAME", parentPath + "数据图表/");
			parameters3.add("FOLDER_NAME", "数据图表");
			parameters3.add("CLASS", "net");
			parameters3.add("USER_ID", userId);
			parameters3.add("CREATE_USER", userId);
			parameters3.add("IMG", "net");
			parameters3.add("RELATION_FOLDER", tempIds);
			parameters3.add("CREATE_TIME", new Date());
			cc.add(sql3);

			// 历史报告

			Sql sql4 = new Sql(
					"insert into g_folder(ID,NAME,FOLDER_NAME,CLASS,USER_ID,CREATE_USER,IMG,READ_SQL,CREATE_TIME)values(?,?,?,?,?,?,?,?,?)");
			Parameters parameters4 = sql4.getParameters();

			String readSql = "SELECT g_file_relaction.ID,CONCAT('" + parentPath
					+ "历史报告/',IFNULL(g_file_relaction.FILE_NAME,g_file.FILE_NAME)) AS NAME, "
					+ " SIZE,g_file.CREATE_TIME,'1' AS FileType, "
					+ " IFNULL(g_file.FILE_PATH,CONCAT(g_folder.NAME,IFNULL(g_file_relaction.FILE_NAME,g_file.FILE_NAME))) AS Path,'' AS IMG,g_file.CLASS "
					+ " FROM g_file_relaction " + " LEFT OUTER JOIN g_folder ON g_file_relaction.FOLDER_ID=g_folder.ID "
					+ " LEFT OUTER JOIN cb_report ON g_file_relaction.ID=cb_report.OFFICIAL_REPORT_ID "
					+ " LEFT OUTER JOIN g_file ON g_file_relaction.FILE_ID=g_file.ID " + " WHERE cb_report.CREATE_USER='"
					+ userId + "'";

			parameters4.add("ID", ID.getGuid());
			parameters4.add("NAME", parentPath + "历史报告/");
			parameters4.add("FOLDER_NAME", "历史报告");
			parameters4.add("CLASS", "net");
			parameters4.add("USER_ID", userId);
			parameters4.add("CREATE_USER", userId);
			parameters4.add("IMG", "net");
			parameters4.add("READ_SQL", readSql);
			// parameters4.add("RELATION_FOLDER", tempIds);
			parameters4.add("CREATE_TIME", new Date());
			cc.add(sql4);

			if (SqlSessionManager.execute(cc)) {
				return true;
			}
		} catch (Exception e) {
			LoggerHelper.error(logger, e, "");
		}

		return false;
	}

	/**
	 * 添加一个签名目录
	 * 
	 * @return
	 * @
	 */
	public boolean addSignDir(String userId)  {
		String path = CebaPathUtil.getSignDirPath(userId);
		try {
			if (!SqlSessionManager.existRecord("g_folder", "NAME='"+path+"'")) {
				IStore store = StoreManager.create("g_folder");
				XObject object = new XObject("ID", ID.getGuid());
				object.put("NAME", path);
				object.put("FOLDER_NAME",TextConstants.REPORT_ATTACHES);
				object.put("USER_ID", userId);
				object.put("CLASS", FileClassConstants.SIGN);
				object.setCreateTime();
				object.setCreateUser();

				if (store.insert(object) > 0) {
					return true;
				}
			}
		} catch (Exception e) {
			LoggerHelper.error(logger, e, "");
		}
		return false;
	}
	/**
	 * 报告管理人的报告模板
	 * 
	 * @return
	 * @
	 */
	public boolean addReportTemplateDir(String userId)  {
		String path = CebaPathUtil.getReportTemplatePath(userId);

		try {
			if (!existDirByUser(path,userId)) {
				IStore store = StoreManager.create("g_folder");
				XObject object = new XObject("ID", ID.getGuid());
				object.put("NAME", path);
				object.put("FOLDER_NAME", TextConstants.REPORT_TEMPLATES);
				object.put("USER_ID", userId);
				object.put("CLASS", FileClassConstants.REPORTTEMPLATE);
				object.setCreateTime();
				object.setCreateUser();

				if (store.insert(object) > 0) {
					return true;
				}
			}
		} catch (Exception e) {
			LoggerHelper.error(logger, e, "");
		}
		return false;

	}
	
	/**
	 * 获取一个报告下面的所有PDF文件，主要是作为正式报告
	 * 
	 * @return
	 * @
	 */
	public String getReleaseReportListJson(String reportId,String userId)  {
		// ?未完成
		String path = "/" + userId + "/" + reportId + "/";
		try {
			Sql sql = new Sql("SELECT g_file_relaction.ID,IFNULL(g_file_relaction.FILE_NAME,g_file.FILE_NAME) AS NAME"
					+ " FROM g_file_relaction " + " LEFT OUTER JOIN g_folder ON g_file_relaction.FOLDER_ID=g_folder.ID "
					+ " LEFT OUTER JOIN g_file ON g_file_relaction.FILE_ID=g_file.ID "
					+ " WHERE g_folder.NAME LIKE '"+path+"%' " + " AND (g_file.EXT_NAME IN ('pdf','doc','docx'))");
			DataTable dt = SqlSessionManager.getDataTable(sql);

			if (dt != null && dt.getRowCount() > 0) {
				return dt.toJSONArrayString();
			}
		} catch (Exception e) {
			LoggerHelper.error(logger, e, "");
		}

		return "";
	}
	
	/**
	 * 获取一个报告下面的所有PDF文件，主要是作为正式报告
	 * 签发草稿验证 查询编制和审核已经签名的报告
	 * @return
	 * @
	 */
	public String getReleaseReportRoleListJson(String reportId,String userId)  {
		
		try{
			Sql sql=new Sql("select CREATE_USER from cb_report Where id=?");
			sql.addParameter(reportId);
			DataTable dt = SqlSessionManager.getDataTable(sql);
			String createUser=dt.getRow(0).getString("CREATE_USER");
			String path = "/" + createUser + "/" + reportId + "/";
			sql = new Sql("SELECT g_file_relaction.ID,IFNULL(g_file_relaction.FILE_NAME,g_file.FILE_NAME) AS NAME"
				/*+ ", IFNULL(SIGNED_FILE_ID,IFNULL(STAMP_FILE_ID,IFNULL(i_table_attach.CUR_FILE_ID,i_table_attach.WORKFLOW_FILE_ID)))"
				+ " AS WORKFLOW_FILE_ID ,IFNULL(i_table_attach.CUR_FILE_ID,i_table_attach.WORKFLOW_FILE_ID) AS FileID"*/
				+ " FROM g_file_relaction " + " LEFT OUTER JOIN g_folder ON g_file_relaction.FOLDER_ID=g_folder.ID "
				+ " LEFT OUTER JOIN g_file ON g_file_relaction.FILE_ID=g_file.ID  RIGHT OUTER JOIN i_table_attach ON i_table_attach.OFFICIAL_REPORT_ID=g_file_relaction.ID"
				+ " WHERE g_folder.NAME LIKE '"+path+"%' " + " AND (g_file.EXT_NAME IN ('pdf','doc','docx'))");
			dt = SqlSessionManager.getDataTable(sql);
			if (dt != null && dt.getRowCount() > 0) {
				return dt.toJSONArrayString();
			}
		} catch (Exception e) {
			LoggerHelper.error(logger, e, "");
		}

		return "";
	}
	
	
	
	/**
	 * 更加ID获取文件url地址,ID可能是报告ID或关联文件ID，文件ID
	 * 
	 * @return
	 * @
	 */
	public String getFileUrlPath(String id) {
		String path = "";
		try {
			DataTable dt = getFileDataTable(id);
			if (dt != null && dt.getRowCount() > 0) {
				path = dt.getRow(0).getString("VIRTUAL_PATH");
			}
		} catch (Exception e) {
			LoggerHelper.error(logger, e, "");
		}

		return path;
	}
	
	/**
	 * 更加ID获取文件url地址
	 * 
	 * @return
	 * @throws Exception
	 */
	public String getFolderUrlPath(String id) throws Exception{
		return SqlSessionManager.getFieldStringValue("SELECT NAME FROM g_folder WHERE ID='"+id+"'");
	}
	
	
	/**
	 * 根据ID获取文件物理地址,ID可能是报告ID或关联文件ID，文件ID
	 * 
	 * @return
	 */
	public GFile getFilePath(String id)  {
		GFile gFile = new GFile();
		try {
			DataTable dt = getFileDataTable(id);
			if (dt != null && dt.getRowCount() > 0) {
				copyDataRowToGFile(dt.getRow(0), gFile);
				return gFile;
			}
		} catch (Exception e) {
			LoggerHelper.error(logger, e, "");
		}
		return null;
	}
	
	
	/**
	 * 根据Id获取文件信息
	 * @param id
	 * @return
	 */

	public List<VFileObject> getFileInfosById(String id)  {
		if (StringUtil.isEmptyString(id)) {
			return null;
		}
		List<VFileObject> vfList = new ArrayList<VFileObject>();
		try {
			Sql sql = new Sql("SELECT g_file.*,g_file_relaction.ID AS RELATION_FILE_ID,"
					+ " g_file_relaction.FILE_NAME AS RELATION_FILE_NAME,g_file_relaction.FOLDER_ID FROM g_file"
					+ " LEFT OUTER JOIN g_file_relaction ON g_file.ID=g_file_relaction.FILE_ID "
					+ " WHERE g_file_relaction.ID='"+id+"'");

			DataTable dt = SqlSessionManager.getDataTable(sql);
			if(dt !=null && dt.getRowCount() >0){
				for( DataRow dr:dt){
					VFileObject vf = new VFileObject();
					copyGFileDataRowToVFileObject(dr, vf);
					vf.setFileRelactionId(dr.getString("RELATION_FILE_ID"));
					vf.setFileRelactionName(dr.getString("RELATION_FILE_NAME"));
					vf.setFolderId(dr.getString("FOLDER_ID"));
					vfList.add(vf);
				}
				return vfList;
			}
			if (dt ==null || (dt!=null && dt.getRowCount() <= 0) ) {
				// 再查文件表
				Sql sql2 = new Sql("SELECT g_file.*,g_file.FILE_NAME AS RELATION_FILE_NAME FROM g_file WHERE ID='"+id+"'");
				dt = SqlSessionManager.getDataTable(sql2);
				if(dt !=null && dt.getRowCount() >0){
					for( DataRow dr:dt){
						VFileObject vf = new VFileObject();
						copyGFileDataRowToVFileObject(dr, vf);
						vf.setFileRelactionName(dr.getString("RELATION_FILE_NAME"));
						vfList.add(vf);
					}
					return vfList;
				}
			}
		} catch (Exception e) {
			LoggerHelper.error(logger, e, "");
			return null;
		}
		return null;
	}
	
	/**
	 * 获取一个文件的datatable文件，同时他多出来一个关联文件名g_file_relaction.FILE_NAME AS
	 * RELATION_FILE_NAME
	 * 
	 * @param id
	 * @return
	 */

	public DataTable getFileDataTable(String id)  {

		if (StringUtil.isEmptyString(id)) {
			return null;
		}
		try {
			Sql sql = new Sql("SELECT g_file.*,g_file_relaction.ID AS RELATION_FILE_ID,"
					+ " g_file_relaction.FILE_NAME AS RELATION_FILE_NAME,g_file_relaction.FOLDER_ID FROM g_file"
					+ " LEFT OUTER JOIN g_file_relaction ON g_file.ID=g_file_relaction.FILE_ID "
					+ " WHERE g_file_relaction.ID='"+id+"'");
			DataTable dt = SqlSessionManager.getDataTable(sql);
			if (dt ==null || (dt!=null && dt.getRowCount() <= 0) ) {
				// 再查文件表
				Sql sql2 = new Sql("SELECT g_file.*,g_file.FILE_NAME AS RELATION_FILE_NAME FROM g_file WHERE ID='"+id+"'");
				dt = SqlSessionManager.getDataTable(sql2);
			}
			return dt;
		} catch (Exception e) {
			LoggerHelper.error(logger, e, "");
			return null;
		}
	}
	
	/**
	 * 把一个文件添加到数据库中,并建立文件关联
	 * 
	 * @param fileRelationId
	 *            ID，如果为空，自动获取
	 * @param fileId
	 *            文件ID，必须存在；
	 * @param fileName
	 *            文件名
	 * @param folderId
	 *            文件目录，必须存在；；
	 * @return
	 * @throws Exception
	 */

	public Boolean addFileRelationRecord(String fileRelationId, String fileId, String fileName, 
			String folderId,String flag,String userId,String storageId){

		if (fileId.equals("") || fileId == null/* || folderId.equals("") || folderId == null*/) {
			return false;
		}

		try {
			if (fileRelationId == null || fileRelationId.equals("")) {
				fileRelationId = ID.getGuid();
			}

			IStore store = StoreManager.create("g_file_relaction");
			XObject object = new XObject("g_file_relaction");
			object.put("ID", fileRelationId);
			object.put("RID", userId);
			object.put("FOLDER_ID", folderId);
//			object.put("FILE_NAME", getFileNameInFolder(CebaFileManageUtil.filterFileName(fileName),folderId));
			object.put("FILE_NAME", CebaFileManageUtil.filterFileName(fileName));
			object.put("FILE_ID", fileId);
			object.put("FLAG", flag);
			object.put("USER_ID", userId);
			object.put("STORAGE_ADDRESS_ID", storageId);
			object.setCreateTime();
			object.setCreateUser();

			if (store.insert(object) > 0) {
				return true;
			}
		} catch (Exception e) {
			LoggerHelper.error(logger, e, "");
		}

		return false;
	}
	
	/**
	 * 更新一个relation文件的相关的签名Id
	 * 
	 * @param fileRelationId
	 * @param signFileId 签名文件的g_file.ID
	 * @return
	 * @throws Exception
	 */

	public Boolean updataRelationFileSign(String fileRelationId,String signFileId){

		try {
			if (fileRelationId == null || fileRelationId.equals("")) {
				fileRelationId = ID.getGuid();
			}

			IStore store = StoreManager.create("g_file_relaction");
			IObject object = store.get(fileRelationId);
			object.put("SIGN_FILE_ID", signFileId);

			if (store.update(object) > 0) {
				return true;
			}
		} catch (Exception e) {
			LoggerHelper.error(logger, e, "");
		}

		return false;
	}

	/**
	 * 把一个文件添加到g_file中
	 * 
	 * @return
	 * @throws Exception
	 */
	public Boolean addFileRecord(GFile gf){
		try {
			if (StringUtil.isEmptyString(gf.getId())) {
				gf.setId(ID.getGuid());
			}
			String  text = CebaFileManageUtil.getFileContent(gf.getFilePath());
			gf.setTextContent(text);
			if (addFile(gf)) {
				return true;
			}
		} catch (Exception e) {
			LoggerHelper.error(logger, e, "");
		}

		return false;
	}
	
	
	/**
	 *当pdf报告中的内容插入到g_file 出现特殊字符  无法插入的零时解决办法
	 * 
	 */
	public Boolean addFileRecordEorr(GFile gf){
		try {
			if (StringUtil.isEmptyString(gf.getId())) {
				gf.setId(ID.getGuid());
			}
			if (addFile(gf)) {
				return true;
			}
		} catch (Exception e) {
			LoggerHelper.error(logger, e, "");
		}
		return false;
			
	}
	
	/**
	 * 把一个文件添加到g_file中，并且闯入文档内容，主要用于一些已经读取过全文的，做盖章、签名等文档添加到g_file
	 * 
	 * @return
	 * @throws Exception
	 */
	public Boolean addFileRecordByDocumentText(GFile gf){
		try {
			if (StringUtil.isEmptyString(gf.getId())) {
				gf.setId(ID.getGuid());
			}
			if (addFile(gf)) {
				return true;
			}
			
		} catch (Exception e) {
			LoggerHelper.error(logger, e, "");
		}

		return false;
	}
	

	/**
	 * 把一个文件添加到数据库中insert语句,不写读取报告内容
	 * 
	 * @return
	 * @throws Exception
	 */
	public Boolean addFileRecordNoDocumentText(GFile gf)  {

		try {
			if (StringUtil.isEmptyString(gf.getId())) {
				gf.setId(ID.getGuid());
			}

			gf.setTextContent("");
			if (addFile(gf)) {
				return true;
			}
		} catch (Exception e) {
			LoggerHelper.error(logger, e, "");
		}

		return false;
	}

	/**
	 * 拷贝文件
	 * @param relactionFileId 要拷贝文件的关联ID
	 * @param folderId 拷贝目录的ID
	 * @param fileName 拷贝的文件名
	 * @return
	 * @throws Exception
	 */
	public Boolean copyFile(String relactionFileId, String folderId, String fileName,String loginUserId)  {

		try {
			if (relactionFileId != null && !relactionFileId.equals("")) {
				GFileRelaction gfr = getGFileRelactionById(relactionFileId);
				if (gfr != null ) {
					
					if(StringUtil.isEmptyString(fileName)){
						fileName = gfr.getFileName();
						
					}
					
					GFileRelaction ngfr = new GFileRelaction();
					GFileRelaction.copyGFileRelactionToGFileRelaction(gfr, ngfr);
					ngfr.setId(ID.getGuid());
					ngfr.setRId(loginUserId);
					ngfr.setFolderId(folderId);
					ngfr.setFileName(getFileNameInFolder(fileName,folderId));
					ngfr.setFlag(FileFlagConstants.COPY);
					ngfr.setSignFileId("");
					ngfr.setUserId(loginUserId);
					ngfr.setCreateUser(loginUserId);
					return addGFileRelaction(ngfr);

				}
			}
		} catch (Exception e) {
			LoggerHelper.error(logger, e, "");
		}

		return false;// 1代表执行失败
	}
	
	/**
	 * 在一个目录中是否存在相同文件名，如果存在这把这个文件名更改，主要用于复制文件，添加FM记录
	 * @param fileName 文件名
	 * @param folderId 目录ID
	 * @return
	 */
	public String getFileNameInFolder(String fileName,String folderId) {
		try {
			Sql sql1 = new Sql("SELECT * FROM g_file_relaction WHERE FOLDER_ID=? AND FILE_NAME = '" + fileName + "'");
			sql1.addParameter("FOLDER_ID", folderId);
			int c = SqlSessionManager.getDataTable(sql1).getRowCount();
			if(c>0){
				String fName=fileName;
				String[] arr=fileName.split("\\.");
				for (int i = 1; i < 10000000; i++) {
					if(arr.length>=2){
						fileName=fName.replace("."+arr[arr.length-1], "")+"-副本 "+i+"."+arr[arr.length-1];
					}
					else {
						fileName=fileName+"_副本"+i;
					}
					sql1 = new Sql("SELECT * FROM g_file_relaction WHERE FOLDER_ID=? AND FILE_NAME = '" + fileName + "'");
					sql1.addParameter("FOLDER_ID", folderId);
					
					if(SqlSessionManager.getDataTable(sql1).getRowCount()<=0){
						break;
					}
				}
			}
		} catch (Exception e) {
			LoggerHelper.error(logger, e, "");
		}
		return fileName;
	}
	
	
	/**
	 * 拷贝目录
	 * @param copyFolderId 要拷贝目录ID
	 * @param toFolderId 目标目录的ID
	 * @param name 拷贝目录名
	 * @return
	 * @throws Exception
	 */
	public Boolean copyFolder(String copyFolderId, String toFolderId, String name,String userId) {

		try {
			if (!StringUtil.isEmptyString(copyFolderId)) {
				GFolder gf = getGFolderByConditon(" ID='"+copyFolderId+"'", "*");
				
				if ( gf != null ) {
					String toFmPath=getFieldValue("g_folder",toFolderId,"NAME");
					if(toFmPath==null || toFmPath.equals("")){
						return false;
					}
					String copyFolderName = gf.getFolderName();
					if(StringUtil.isEmptyString(name)){
						name=copyFolderName;
						if(name.length()==32){
							//如果文件名32位,并且文件类型不为空,说明以报告号作为目录名
							if(!("").equals(gf.getClassS())){
								String _folderName= getFieldValue("cb_report",name,"NO"); 
								if(_folderName!=null && !_folderName.equals("")){
									//fmPath=fmPath.replace(folderName, _folderName);
									name=_folderName;
								}
							}
						}
					}
					int c = SqlSessionManager.getDataTable("SELECT ID FROM g_folder WHERE NAME LIKE '"+toFmPath+name+"%' AND FOLDER_NAME LIKE '"+name+"%'").getRowCount();
					String newFolderName=name;
					if(c>0){
						newFolderName=name+TextConstants.DEPUTY_FILES+c;
					}

					String rootFmPath= gf.getName();
					String fmRootParentPath= CebaFileManageUtil.getFmParentPath(rootFmPath);
					
					DataTable folderDt=SqlSessionManager.getDataTable("SELECT * FROM g_folder WHERE NAME LIKE '" + rootFmPath + "%'");
					String folderId="",fmPath="",folderName="";
					for (DataRow row : folderDt.getRows()) {
						folderId=ID.getGuid();
						//替换成为新的路径
						fmPath=toFmPath+row.getString("NAME").replace(fmRootParentPath, "");
						fmPath=fmPath.replace(copyFolderName, name).replace(name, newFolderName);
						if(name.equals(row.getString("FOLDER_NAME"))){
							//如果当前目录和复制到目录同名
							folderName=newFolderName;
						}
						else{
							folderName="";
						}
						GFolder nGF = GFolder.createGFolder(folderId, fmPath, folderName, "", "",userId);
						addFolder(nGF);//新增一个目录
						DataTable dtFile=SqlSessionManager.getDataTable("SELECT * FROM g_file_relaction WHERE FOLDER_ID='"+row.getString("ID")+"'");
						if(dtFile!=null && dtFile.getRowCount()>0){
							for (DataRow rowFile : dtFile.getRows()) {
								rowFile.set("ID",ID.getGuid());
								rowFile.set("FOLDER_ID",folderId);
								rowFile.set("FLAG","copy");
								rowFile.set("SIGN_FILE_ID","");
							}
							dtFile.getColumn("ID").setPrimaryKey(true);
							DataTableSqlBuilder sqlBuilder = new DataTableSqlBuilder(dtFile);
							SqlDataSource sqlDataSource = sqlBuilder.toDataSource(DBAction.AddNew);
							sqlDataSource.insert();
						}
					}
					return true;
					
				}
			}
		} catch (Exception e) {
			LoggerHelper.error(logger, e, "");
		}
			
		return false;
	}
	
	
	/**
	 * 当前文件夹是否有权限操作
	 * 
	 * @param pathOrID
	 *            路径或ID
	 * @return
	 */
	public Boolean isMyFolder(String pathOrID,String userId) {
		try {
			Sql sql = new Sql("SELECT * FROM g_folder WHERE (ID='"+pathOrID+"' OR NAME='"+pathOrID+"') AND USER_ID='"+userId+"'");

			DataTable dt = SqlSessionManager.getDataTable(sql);

			if (dt != null && dt.getRowCount() > 0) {
				return true;
			}
		} catch (Exception e) {
			LoggerHelper.error(logger, e, "");
		} 
		return false;

	}

	/**
	 * 当前文件是否是我创建的
	 * 
	 * @param pathOrID
	 *            路径或ID
	 * @return
	 */
	public Boolean isMyFile(String pathOrID,String userId) {
		try {
			Sql sql = new Sql("SELECT * FROM g_file WHERE ID='"+pathOrID+"' AND USER_ID='"+userId+"'");	

			DataTable dt = SqlSessionManager.getDataTable(sql);

			if (dt != null && dt.getRowCount() > 0) {
				return true;
			} else {
				// 如果路径有问题，可能传过来的是ID
				sql = new Sql("SELECT * FROM g_file WHERE FILE_PATH='"+pathOrID+"' AND USER_ID='"+userId+"'");
				dt = SqlSessionManager.getDataTable(sql);

				if (dt != null && dt.getRowCount() > 0) {
					return true;
				}
			}
		} catch (Exception e) {
			LoggerHelper.error(logger, e, "");
		}

		return false;
	}

	/**
	 * 文件转PDF
	 * 
	 *            路径或ID
	 * @return
	 * @throws Exception
	 */
	public Boolean toPDF(String fileID, String folderID ,String loginUserId,String storageAddressId,String outPath,String verPath)  {
		try {
			DataTable dt = getFileDataTable(fileID);
			DataRow row = dt.getRow(0);
			String path = PDFUtils.wordToPdf(row.getString("FILE_PATH"),outPath);
			// 如果返回时空字符串，说明转PDF不成功
			if (!path.equals("")) {

				String id = ID.getGuid();
				String fileName = row.getString("RELATION_FILE_NAME");
				fileName = FileHelper.getFileName(fileName) + "_" + ID.get6bID().toString() + ".pdf";

				GFile gf = GFile.createGFile(id, fileName, GFileContentTypeEnum.PDF.getContentType(), "", path, FileClassConstants.TOPDF,loginUserId,storageAddressId,verPath);
				if (!addFile(gf)) {
					addFileRecord(gf);
				}
				if (addFileRelationRecord(ID.getGuid(), id, fileName, folderID, FileFlagConstants.CREATE,loginUserId,storageAddressId)) {
					return true;
				}

			}
		} catch (Exception e) {
			LoggerHelper.error(logger, e, "");
		}

		return false;

	}
	
	/**
	 * 添加一个目录
	 * 
	 * @return
	 * @throws Exception
	 */
	public boolean addFolder(GFolder gf/*,String id, String path, String folderName, String classString,String userId*/) {

		try {
			if (StringUtil.isEmptyString(gf.getId())) {
				gf.setId(ID.getGuid());
			}
			String path = gf.getName();
			if (!existDirByUser(gf.getName(),gf.getCreateUser())) {
				String folderName = gf.getFolderName();
				if(folderName.equals("")){
					String[] arr = path.split("/");
					folderName = arr[arr.length - 1];
				}
				String pid="";
				String parentFmPath= CebaFileManageUtil.getFmParentPath(path);
				if(!parentFmPath.equals("")){
					GFolder gff = getGFolderByConditon("NAME='" + parentFmPath + "'", "ID");
					if(gff !=null){
						pid= gff.getId();
					}
						
				}
				gf.setPId(pid);
				folderName= CebaFileManageUtil.filterFileName(folderName);
				gf.setFilePath(folderName);
				gf.setFolderName(folderName);
				return addGFolder(gf);
			}
		} catch (Exception e) {
			LoggerHelper.error(logger, e, "");
		}
		return false;
	}
	
	
	/**
	 * 根据虚拟路径建立一组目录
	 * 
	 * @param path
	 *            目录路径
	 * @param classString
	 *            分类
	 * @return
	 * @throws Exception
	 */
	public Map<String, String> addFolders(String path,String parentPath,String fmRootFolderPath, String classString,String userId) {

		Map<String, String> dic = new HashMap<String, String>();
		try {
			String[] arr = path.split("/");
			String newPath = "/";
			String nP = "";
			String id = "";

			for (String name : arr) {
				if (!StringUtil.isEmptyString(name)) {
					if(new File(parentPath+name).isDirectory() || fmRootFolderPath.contains(name)
							|| new File(parentPath+nP).isDirectory()){
						newPath = newPath + name + "/";
						nP = newPath;
						nP = nP.replace(fmRootFolderPath, "");
						GFolder gf = getGFolderByConditon("NAME='" + newPath + "'", "ID,NAME");
						if (gf != null ) {
							dic.put(gf.getName(),gf.getId());
						} else {
							id = ID.getGuid();
							GFolder gfolder = GFolder.createGFolder(id,newPath,name,"",classString,userId);
							if(addFolder(gfolder)){
								dic.put(newPath, id);
							}
						
						}
					}
				}
			}
		} catch (Exception e) {
			LoggerHelper.error(logger, e, "");
		}

		return dic;
	}
	
	/**
	 * 目录更名
	 * 
	 * @param oldPath
	 *            原目录路径
	 * @param newFolderName
	 *            新目录名
	 * @param classString
	 *            分类
	 * @return
	 * @throws Exception
	 */
	public boolean updateFolderName(String id, String oldPath, String newFolderName, String classString,String userId) {

		if (id == null || id.equals("")) {
			return false;
		}
		try {
			int pos = oldPath.lastIndexOf("/");
			String parentPath = oldPath.substring(0, pos + 1);
			String newFolderPath = parentPath + newFolderName + "/";
			GFolder gFolder = getGFolderByConditon("g_folder.NAME='" + newFolderPath + "'", "ID");
			if (gFolder !=null ) {
				return false;
			}

			if (!existDirByUser(oldPath,userId)) {
				newFolderName = newFolderName.replace("/", "").replace("\\", "").replace("|", "");
				Sql sql = new Sql(
						"SELECT ID,NAME,FOLDER_NAME,CLASS from g_folder  " + "WHERE NAME LIKE '" + oldPath + "%' ");
				DataTable dt = SqlSessionManager.getDataTable(sql);
				String folderPath = "";
				
				String tempPath = "";
				for (DataRow row : dt.getRows()) {
					folderPath = row.getString("NAME");
					if (oldPath.replace("/", "").equals(folderPath.replace("/", ""))) {
						row.set("FOLDER_NAME", newFolderName);
						row.set("CLASS", classString);
					}
					tempPath = row.getString("NAME").replace(oldPath, newFolderPath).replace("//", "/");
					row.set("NAME", tempPath);
				}
				dt.getColumn("ID").setPrimaryKey(true);
				DataTableSqlBuilder sqlBuilder = new DataTableSqlBuilder(dt);
				SqlDataSource sqlDataSource = sqlBuilder.toDataSource(DBAction.Update);
				Result result = new Result();
				sqlDataSource.update(result);
				//修改之前是if (result.isSucceed()) {
				if (!result.isSucceed()) {
					return true;
				}
			}
		} catch (Exception e) {
			LoggerHelper.error(logger, e, "");
		}
		return false;
	}
	
	/**
	 * FM文件更名
	 * @param id
	 * @param oldPath
	 * @param newName
	 * @return
	 */
	public boolean updateFmFileName(String id, String oldPath, String newName,String userId){
		try {
			String folderId=SqlSessionManager.getFieldStringValue("SELECT FOLDER_ID FROM g_file_relaction WHERE ID='"+id+"'");
			if(folderId!=null &&  !folderId.equals("")){
				if (SqlSessionManager.getFieldLongValue("SELECT COUNT(ID) AS C FROM g_file_relaction WHERE  FILE_NAME='" + newName + "' AND FOLDER_ID='"+folderId+"'") > 0) {
					return false;
				}
			}
			Sql sql = new Sql("UPDATE g_file_relaction SET FILE_NAME=? WHERE ID=? AND CREATE_USER=?");
			sql.addParameter("FILE_NAME", newName);
			sql.addParameter("ID", id);
			sql.addParameter("CREATE_USER", userId);
			if (SqlSessionManager.execute(sql)) {
				return true;
			}
		} catch (Exception e) {
			LoggerHelper.error(logger, e, "");
		}
		return false;
	}
	
	/**
	 * 把一个目录打包成Zip文件
	 * 
	 * @param folderID
	 *            文件目录ID
	 * @return
	 * @throws Exception
	 */
	public String getFolderZip(String folderID,String zipPath,String type)  {

		String folderName = "";
		try {
			IStore store = StoreManager.create("g_folder");
			IObject object = store.get(folderID);

			if (object != null && object.size() > 0) {
				if (!"net".equals(object.getString("CLASS"))) {
					if (folderName.equals("")) {
						folderName = object.getString("FOLDER_NAME");
					}
					zipPath = getFolderZip(object.getString("NAME"), folderName,zipPath,null);
				}
			}
		} catch (Exception e) {
			LoggerHelper.error(logger, e, "");
		}

		return zipPath;
	}
	
	/**
	 * 把一个目录打包成Zip文件
	 * 
	 * @param folderPath
	 * @param folderName
	 *            压缩包名字
	 * @return -1代表打包文件超过25M，
	 * @throws Exception
	 */
	public String getFolderZip(String folderPath, String folderName,String zipPath ,String type)   {

		try {
			int iSize= getFolderSize(folderPath);
			//最多只能打包25M的文件
			if(iSize>CebaConfig.ZIP_DOWN_MAX_SIZE){
				return "-1";
			}

			zipPath+="/" + folderName + ".zip";
			CebaFileManageUtil.createDirectory(zipPath);
			// ?如果是空目录，zip包里面现在不存在
			Sql sql = new Sql("SELECT g_file_relaction.ID,"
					+ " REPLACE(CONCAT(g_folder.NAME,IFNULL(g_file_relaction.FILE_NAME,g_file.FILE_NAME)), '" + folderPath
					+ "', '') AS NAME,"
					+ " IFNULL(g_file.FILE_PATH,CONCAT(g_folder.NAME,IFNULL(g_file_relaction.FILE_NAME,g_file.FILE_NAME))) AS PATH  "
					+ " FROM g_file_relaction  " + " LEFT OUTER JOIN g_folder ON g_file_relaction.FOLDER_ID=g_folder.ID "
					+ " LEFT OUTER JOIN g_file ON g_file_relaction.FILE_ID=g_file.ID " + " WHERE g_folder.NAME LIKE '"
					+ folderPath + "%'");

			DataTable dt = SqlSessionManager.getDataTable(sql);
			String filePath = "";
			Zip zip = new Zip(zipPath);

			for (DataRow row : dt.getRows()) {
				filePath = row.getString("PATH");
				if (FileHelper.exists(filePath)) {
					zip.zip(filePath, folderName + "/" + row.getString("NAME"));

				}
			}

			zip.close();

			return zipPath;
		} catch (Exception e) {
			LoggerHelper.error(logger, e, "");
			return "";
		}
	}
	
	/**
	 * 下载一组选择的文件,包括文件夹
	 * @param jsonFiles 文件json
	 * @param folderName 压缩包名，也是文件夹名
	 * @return -1代表打包文件超过25M，
	 * @throws Exception
	 */
	public String getZipFiles(String jsonFiles, String folderName,String zipPath )  {
		try {

			int iSize= getFilesSize(jsonFiles);
			//最多只能打包25M的文件
			if(iSize>CebaConfig.ZIP_DOWN_MAX_SIZE){
				return "-1";
			}
			String sql="";
			String parentPath="";
			String folderPath="";
			CebaFileManageUtil.createDirectory(zipPath);
			 JSONArray json=new JSONArray (jsonFiles);
			 for(int i=0;i<json.length();i++){  
				 JSONObject j =json.getJSONObject(i);  
				 if(j.getString("type").equals("dir")){
					 folderPath=getFolderUrlPath(j.getString("id"));
					 parentPath= CebaFileManageUtil.getFmParentPath(folderPath);
					 if(!parentPath.equals("")){
						 sql+=" SELECT g_file_relaction.ID,"
								+ " REPLACE(CONCAT(g_folder.NAME,IFNULL(g_file_relaction.FILE_NAME,g_file.FILE_NAME)), '" + parentPath
								+ "', '') AS NAME,"
								+ " IFNULL(g_file.FILE_PATH,CONCAT(g_folder.NAME,IFNULL(g_file_relaction.FILE_NAME,g_file.FILE_NAME))) AS PATH  "
								+ " FROM g_file_relaction  " + " LEFT OUTER JOIN g_folder ON g_file_relaction.FOLDER_ID=g_folder.ID "
								+ " LEFT OUTER JOIN g_file ON g_file_relaction.FILE_ID=g_file.ID " + " WHERE g_folder.NAME LIKE '"
								+ folderPath + "%' UNION";
					 }
				 }
				 else {
					sql+=" SELECT g_file_relaction.ID,IFNULL(g_file_relaction.FILE_NAME,g_file.FILE_NAME) AS NAME,"
							+ " g_file.FILE_PATH AS PATH FROM g_file_relaction"
							+ " LEFT OUTER JOIN g_file ON g_file.ID=g_file_relaction.FILE_ID "
							+ " WHERE g_file_relaction.ID='"+j.getString("id")+"' UNION";
				 }
			  }
			if(!sql.equals("")){
				sql=sql.substring(0, sql.length()-5);
				DataTable dt = SqlSessionManager.getDataTable(sql);
				String filePath = "";
				Zip zip = new Zip(zipPath);

				for (DataRow row : dt.getRows()) {
					filePath = row.getString("PATH");
					if (FileHelper.exists(filePath)) {
						zip.zip(filePath, folderName + "/" + row.getString("NAME"));
					}
				}

				zip.close();

				return zipPath;
			}
		} catch (Exception e) {
			LoggerHelper.error(logger, e, "");
		}
		 
		return "";
	}

	/**
	 * 把一个压缩包解压,并转存到文件管理器中（转数据库）
	 * 
	 * @param zipPath
	 *            zip包物理路径
	 * @param fmRootFolderPath
	 *            filemanage导入根目录虚拟路径
	 * @return
	 * @throws Exception
	 */
	public Boolean unZipToFileManager(String zipPath, String fmRootFolderPath,String userId,String loginUserId,String toFolderPath,String tempPath,String storageAddressId,String verPath,String fmPath ) {
		try {

			if (!tempPath.equals("")) {

				String sql = "SELECT g_file_relaction.ID,CONCAT(g_folder.NAME,IFNULL(g_file_relaction.FILE_NAME,g_file.FILE_NAME)) AS NAME,"
						+ " IFNULL(g_file.FILE_PATH,CONCAT(g_folder.NAME,IFNULL(g_file_relaction.FILE_NAME,g_file.FILE_NAME))) AS Path"
						+ " FROM g_file_relaction" + " LEFT OUTER JOIN g_folder ON g_file_relaction.FOLDER_ID=g_folder.ID"
						+ " LEFT OUTER JOIN g_file ON g_file_relaction.FILE_ID=g_file.ID" + " WHERE g_folder.NAME LIKE '"
						+ fmRootFolderPath + "%'";

				DataTable dt = SqlSessionManager.getDataTable(sql);

//				String fmPath = "";
				String path = "";
				String copyPath = "";
				String fileName = "";
				String fileId = "";
				String newPath =verPath;
				boolean isNewPath =false;
//				String fmFolderPath = "";
				// String folderId="";

				Map<String, String> dicFolder = new HashMap<String, String>();
				Collection<String> fileAnDirs = FileHelper.listFilesAndDirectorys(tempPath, "");
				Iterator<String> iterator = fileAnDirs.iterator();

				while (iterator.hasNext()) {
					path = iterator.next();
					String fileIds =ID.getGuid();
//					fmPath = tempPath.replace(CebaPathUtil.getPhysicalTempDirPath(), fmRootFolderPath);
					if (CebaFileManageUtil.isFile(path)) {
						fileName = FileHelper.getFileName(path, true);
						//得到新的文件夹路径
//						fmFolderPath = fmPath.replace(fileName, "");
						String folderId = dicFolder.get(fmPath);
						if (folderId == null || folderId.equals("")) {
							dicFolder = addFolders(fmPath, tempPath,fmRootFolderPath, "",userId);
							folderId = dicFolder.get(fmPath);
							if (folderId == null || folderId.equals("")) {
								break;
							}
						}
						Boolean bFileExist = false;
						for (DataRow row : dt.getRows()) {
							// 如果文件名相同，则说明文件已经存在
							if (row.getString("NAME").equals(fmPath)) {
								CebaFileManageUtil.cover(path, row.getString("PATH"));
								bFileExist = true;
								break;
							}
						}
						// 如果数据库目录中不存在
						if (!bFileExist) {
							copyPath = toFolderPath + fileIds + "." + FileHelper.getFileExtName(path);
							verPath=newPath+fileIds + "." + FileHelper.getFileExtName(path);
							FileHelper.copyFile(path, copyPath);
							fileId = ID.getGuid();
							GFile gf = GFile.createGFile(fileId, fileName, "", "", copyPath, "",loginUserId,storageAddressId,verPath);
							addFileRecord(gf);
							addFileRelationRecord("", fileId, fileName, folderId,"create",userId,storageAddressId);
							isNewPath=true;
						}
					}
				}
				if(!isNewPath){
					// 如果是目录
					String folderIds = ID.getGuid();
					File dir = new File(path);
					// folderPath=fmPath;
					GFolder gFolder = GFolder.createGFolder(folderIds, fmPath,  dir.getName(), "", "",userId);
					if (addFolder(gFolder)) {
						dicFolder.put(fmPath, folderIds);
				}
			}
			return true;
			}
		}catch (Exception e) {
			LoggerHelper.error(logger, e, "");
		}

		return false;

	}

	
	/**
	 * 这个文件是否被数字证书签章过，如果SIGN_FILE_MORE设置是true，可以允许同一个文件多签
	 * @param fmFileId g_file_relaction.ID
	 * @param fileId g_file.ID
	 * @return true代表已签过，false代表未签过
	 */
	public Boolean boolSignFMFile(String fmFileId,String fileId) {
		try {
			if(CebaConfig.SIGN_FILE_MORE.equals("false")){
				Sql sql=new Sql("SELECT ID FROM cb_report_sign WHERE RELATION_FILE_ID=? OR FILE_ID=?");
				sql.addParameter("RELATION_FILE_ID", fmFileId);
				sql.addParameter("FILE_ID", fileId);
				DataTable dt=SqlSessionManager.getDataTable(sql);
				if(dt!=null && dt.getRowCount()>0){
					return true;
				}
			}
		} catch (Exception e) {
			LoggerHelper.error(logger, e, "");
		}
		
		return false;
	}
	

	/**
	 * 获取一组文件的大小，包括文件或文件夹
	 * @param filesJson 文件组json
	 * @return -1代表获取不到大小否则都是这组文件的大小
	 */
	public int getFilesSize(String filesJson) {
		try {
			List<VFileObject> vfs=getFMFilesByJson(filesJson);
			return getSize(vfs);
		} catch (Exception e) {
			LoggerHelper.error(logger, e, "");
		}
		return 0;
	}
	
	/**
	 * 获取文件夹的大小
	 * @param folderPath 文件目录路径
	 * @return -1代表获取不到大小否则都是这组文件的大小
	 */
	public int getFolderSize(String folderPath) {
		try {
			List<VFileObject> vfs=getFMFilesListByFolderPath(folderPath,"");
			return getSize(vfs);
		} catch (Exception e) {
			LoggerHelper.error(logger, e, "");
		}
		return 0;
	}
	
	
	public int getSize(List<VFileObject> vfs) throws Exception{
		int iTotalSize=0;
		int iSize=0;
		if(vfs!=null && vfs.size()>0){
			for (VFileObject row : vfs) {
				try {
					iSize= (int) row.getSize();
					iTotalSize=iTotalSize+iSize;
				} catch (Exception e) {
				}
			}
			return iTotalSize;
		}
		return -1;
	}
	
	/**
	 * 删除不需要的缓存文件
	 * 0--成功
	 * 1--没有需要删除的缓存文件
	 * 100--删除时出现异常
	 * 其他情况，返回删除的个数
	 * @return
	 */
	public int deleteTempUse() {
		int count = 0;
		try{
			//查询在g_file_relaction_delete存在而不存在g_file_relaction的数据，
			//同时外联g_file,找到文件的物理路径
			Sql sql = new Sql("select gfrd.FILE_ID,gf.FILE_PATH from g_file_relaction_delete as gfrd "
					+ " LEFT OUTER JOIN g_file AS gf on  gf.ID = gfrd.FILE_ID"
					+ " where gfrd.FILE_ID not IN("
					+ " select gr.FILE_ID from g_file_relaction as gr) ORDER BY gfrd.CREATE_TIME DESC");
			DataTable dt = SqlSessionManager.getDataTable(sql);
			boolean f = false;
			if(dt !=null && dt.getRowCount() >0){
				for(int i = 0 ; i < dt.getRowCount() ; i ++){
					DataRow row = dt.getRow(i);
					String fileId = row.getString("FILE_ID");
					String filePath = row.getString("FILE_PATH");
					if(FileHelper.exists(filePath)){
						f = FileHelper.deleteFile(filePath);
						if(f){
							//删除对应的记录
							f = SqlSessionManager.execute("Delete from g_file_relaction_delete "
									+ " where FILE_ID ='"+fileId+"'");
							if(f){
								f = SqlSessionManager.execute("Delete from g_file "
										+ " where ID ='"+fileId+"'");
								count ++;
							}
						}
					}else if(StringUtil.isEmptyString(filePath) || !FileHelper.exists(filePath)){
						//删除对应的记录
						f = SqlSessionManager.execute("Delete from g_file_relaction_delete "
								+ " where FILE_ID ='"+fileId+"'");
						if(f){
							f = SqlSessionManager.execute("Delete from g_file "
									+ " where ID ='"+fileId+"'");
							count ++;
						}
					}
				}
				if(count == dt.getRowCount() ){
					return count;
				}
			}else{
				return -1;
			}
		}catch(Exception e){
			LoggerHelper.error(logger, e, "");
			return -2;
		}
		return count;
	}
	
	/**
	 * 通过路径寻找folderId
	 * @param path
	 * @return
	 */
	public String getFolderIdByPath(String path) {
		try {
			Sql sql = new Sql("select ID FROM g_folder where NAME = '"+path+"'");
			DataTable dt = SqlSessionManager.getDataTable(sql);
			if(dt !=null && dt.getRowCount() >0){
				return dt.getRow(0).getString("ID");
			}
		} catch (Exception e) {
			LoggerHelper.error(logger, e, "");
		}
		return "";
	}
	
	/*
	 * 根据用户id和目录id获取目录是否创建
	 */
	public long getCountOfFolderById(String userId,String foldId) {
		return getFieldLongValue("SELECT COUNT(g_folder.ID) AS C FROM g_folder WHERE g_folder.USER_ID='"
						+ userId + "' AND ID='" + foldId + "'");
	}
	
	/*
	 * 根据用户id和文件关联id，获取文件
	 */
	public long getCountOfGFileRelactionById(String userId, String fileRelactionId) {
		return getFieldLongValue("SELECT COUNT(ID) AS C FROM g_file_relaction WHERE ID='" + fileRelactionId
						+ "' AND CREATE_USER='" + userId + "'");
	}
	
	/*
	 * 根据目录id获取文件路径
	 */
	public String getPathOfFolderById(String userId, String id) {
		return getFieldStringValue("SELECT NAME from  g_folder WHERE ID='" + id + "'  AND USER_ID='" + userId + "'");
	}
	
	/*
	 * 根据条件获取目录字段值
	 */
	public String getFolderFieldValueByFolderPath(String fieldName,String query) {
		Sql sql = new Sql("SELECT "+fieldName+" FROM g_folder WHERE " + query);
		return SqlSessionManager.getFieldStringValue(sql);
	}

	/*
	 * 根据文件名+目录路径获取文件对象
	 */
	public GFileRelaction getGFRelactionByFolderPathAndFileName(String fileName, String virtualPath) {
		Sql  sql = new Sql("SELECT g_file_relaction.ID,g_file_relaction.FILE_ID,"
				+ " g_file.FILE_PATH,g_file_relaction.CREATE_USER,g_file_relaction.FLAG " 
				+ " FROM g_file_relaction "
				+ " LEFT OUTER JOIN g_folder ON g_file_relaction.FOLDER_ID=g_folder.ID "
				+ " LEFT OUTER JOIN g_file ON g_file_relaction.FILE_ID=g_file.ID  "
				+ " WHERE IFNULL(g_file_relaction.FILE_NAME,g_file.FILE_NAME)='" + fileName
				+ "' AND g_folder.NAME='" + virtualPath + "'");

		DataTable dt = SqlSessionManager.getDataTable(sql);
		GFileRelaction gr = new GFileRelaction();
		if(dt != null && dt.getRowCount() > 0){
			DataRow dr = dt.getRow(0);
			copyDrToGFileRelaction(dr, gr);
			return gr;
		}
		return null;
	}

	/*
	 * 根据条件更新g_file
	 */
	public boolean updateGFileByQuery(String updates,String condition) {
		return SqlSessionManager.execute("UPDATE g_file set "+ updates +" where "+condition);
	}

	/*
	 * 根据用户ID+虚拟路径名获取文件目录
	 */
	public GFolder getGFolderByUserIdAndVirtualPath(String userId, String virtualPath) {
		DataTable dt = SqlSessionManager.getDataTable("SELECT  ID from g_folder  WHERE  USER_ID='"
				+ userId + "' AND NAME='" + virtualPath + "' ");
		GFolder gFolder = new GFolder();
		if(dt != null && dt.getRowCount() > 0){
			DataRow dr = dt.getRow(0);
			copyDrToGFolder(dr, gFolder);
			return gFolder;
		}
		return null;
	}
	/**
	 * 根据id和查询条件获取文件目录
	 * @param id
	 * @param query
	 * @return
	 */
	public GFolder getGFolderByIdAndFields( String id ,String query,String path){
		DataTable dt =null;
		if(StringUtil.isEmptyString(id)){
			dt = SqlSessionManager.getDataTable(" select "+query+" FROM g_folder WHERE NAME='"+path+"'");
		}else{
			dt = SqlSessionManager.getDataTable(" select "+query+" FROM g_folder WHERE ID='"+ id + "'");
		}
		
		GFolder gFolder = new GFolder();
		if(dt != null && dt.getRowCount() > 0){
			DataRow dr = dt.getRow(0);
			copyDrToGFolder(dr, gFolder);
			return gFolder;
		}
		return null;
	}
	/**
	 * 根据 relation id查询 g_file
	 * @param relation_id
	 * @return
	 */
	public JSONObject g_fila_relationGetFile(String relation_id){
		DataTable dt = SqlSessionManager.getDataTable("select * from g_file g,g_file_relaction r where r.id='"+relation_id+"' and g.id=r.FILE_ID");
		if(dt != null && dt.getRowCount() > 0){
			DataRow dr = dt.getRow(0);
			return dr.toJSONObject();
		}
		return null;
	}
	
	
	
	/**
	 * 取得报告的原始文件
	 * @param reportid
	 * @return
	 */
	public JSONArray reportOriginalFile(String reportid){
		DataTable dt = SqlSessionManager.getDataTable("select g.*,r.FILE_NAME as FILE_NAMER,r.ID as RELACTION_ID from i_table_attach i,g_file g,g_file_relaction r "
				+ "where i.CB_REPORT_ID='"+reportid+"' "
				+ "and i.OFFICIAL_REPORT_ID = r.ID and r.FILE_ID=g.ID;");
		return dt.toJSONArray();
	}
	
	
	
	
	/**
	 * 
	 * @param reportId
	 * @return
	 */
	public JSONArray getFileRoleListJson(String reportId){
		Sql sql=new Sql("select g.*,i.OFFICIAL_REPORT_ID from g_file g,i_table_attach i where i.CB_REPORT_ID=? and g.id=i.CUR_FILE_ID");
		sql.addParameter(reportId);
		DataTable dt = SqlSessionManager.getDataTable(sql);
		if(dt != null && dt.getRowCount() > 0){
			return dt.toJSONArray();
		}
		return null;
	}
	/**
	 * 根据 g_file 表的id 取得 g_file_ralation id
	 * @param fileidArray
	 * @return
	 */
	public String getRelationFile(String[] fileidArray){
		StringBuffer fileIdBuffer=new StringBuffer();
		fileIdBuffer.append("(");
		for(int i=0;i<fileidArray.length;i++){
			if(StringUtils.isEmpty(fileidArray[i])){
				continue;
			}
			fileIdBuffer.append("'");
			fileIdBuffer.append(fileidArray[i]);
			fileIdBuffer.append("'");
			fileIdBuffer.append(",");
		}
		fileIdBuffer.append(")");
		fileIdBuffer.replace(fileIdBuffer.length()-2, fileIdBuffer.length(), ")");
		Sql sql=new Sql("select g.ID,IFNULL(r.FILE_NAME,g.FILE_NAME) as FILE_NAME from g_file g "
				+ "LEFT OUTER JOIN g_file_relaction r ON r.FILE_ID = g.ID where g.ID in "+fileIdBuffer.toString());
		DataTable dt = SqlSessionManager.getDataTable(sql);
		if(dt != null && dt.getRowCount() > 0){
			return dt.toJSON();
		}
		return null;
	}
	

	
	public String filePath(String fileID){
		String file_path=SqlSessionManager.getFieldStringValue("SELECT FILE_PATH FROM g_file WHERE ID"
				+ " = (select FILE_ID FROM g_file_relaction WHERE ID='"+fileID+"')");
		return file_path;
	}
	
	public String fileID (String fileID){
	 return SqlSessionManager.getFieldStringValue("select FOLDER_ID FROM g_file_relaction WHERE ID='"+fileID+"'");
	}
	
	
	public String getFieldStringValue(String userId,String reportId) throws Exception{
		String folderId=SqlSessionManager.getFieldStringValue("SELECT ID FROM g_folder WHERE NAME='"+"/" + userId + "/" + reportId + "/"+"'");
		return  folderId;
		
	}
	
	
	/**
	 * @param fileId
	 * @return
	 */
	public  GFileRelaction getFileRelactionById(String fileId){
		Sql sql = new Sql("SELECT FILE_NAME,FOLDER_ID FROM g_file_relaction WHERE ID=?");
		sql.addParameter("ID", fileId);
		DataTable dt =SqlSessionManager.getDataTable(sql);
		GFileRelaction gfr = new GFileRelaction();
		if(dt != null && dt.getRowCount() > 0){
			DataRow dr = dt.getRow(0);
			copyDrToGFileRelaction(dr, gfr);
			return gfr;
		}
		return null;
	}
	

	/**
	 * 判断签名文件是否合格
	 * @param relaction_id
	 */
	public GFileRelaction isSignFile(String relaction_id) {
		Sql sql=new Sql("SELECT FILE_NAME,FLAG FROM g_file_relaction WHERE ID=?");
		sql.addParameter("ID", relaction_id);
		DataTable dt=SqlSessionManager.getDataTable(sql);
		GFileRelaction gfr = new GFileRelaction();
		if(dt != null && dt.getRowCount() > 0){
			DataRow dr = dt.getRow(0);
			copyDrToGFileRelaction(dr, gfr);
			return gfr;
		}
		return null;

	}
	
	/**
	 * @return
	 * @throws Exception
	 */
	public VFileObject getFileIdFilePath(String fileId){
		Sql sql  = new Sql("select f.FILE_PATH,f.VIRTUAL_PATH,r.FILE_NAME from g_file f,g_file_relaction r "
				+ " where f.ID=r.FILE_ID and (f.ID='"+fileId+"' or r.id='"+fileId+"')");
		DataRow row=SqlSessionManager.getDataTable(sql).getRow(0);
		VFileObject vf = new VFileObject();
		vf.setFilePath(row.getString("FILE_PATH"));
		vf.setFileName(row.getString("FILE_NAME"));
		vf.setVirtualPath(row.getString("VIRTUAL_PATH"));
		return vf;
	}
}


